1.Python操作txt文本

文章目录

1.Python读取一个txt文件的内容并将其写入到另一个txt文件

python 复制代码
# -*- encoding:gb2312 -*-
import chardet

def read_write_txt(inputpath, outputpath):
    with open(
            inputpath,
            'rb',
    ) as file:     # rb: 以二进制格式打开一个文件用于只读。
        raw_data = file.read()   # 读出内容用到的是read函数。这个函数的工作原理是依靠一个指针来对内容进行访问的。read方法会用一个指针将文本内容从上到下扫面一遍并且将其输出到内存。扫描完后它的指针是停留在末尾处的。也就是说,如果我们想用read方法访问同一个文件两次,是不可行的。
        detected_encoding = chardet.detect(raw_data)['encoding']  # 返回文件的编码格式。
    with open(inputpath, 'r', encoding=detected_encoding) as infile:
        with open(outputpath, 'w', encoding=detected_encoding) as outfile:
            # # 第一种:读取所有行
            # data1 = infile.readlines()
            # print(data1)
            # # 输出:['好好学习\n', '天天向上\n', '我是一只鱼\n', '哈哈哈']

            # 第二种:每行分开读取
            data2 = []
            for line in infile:
                data_line = line.strip("\n")  # 去除首尾换行符
                data2.append(data_line)
            print(data2)
            # 输出:['好好学习', '天天向上', '我是一只鱼', '哈哈哈']

            # 写入方法
            for line in data2:
                # data = '' + '\t'.join(str(i) for i in line) + '\n'  # 用\t隔开
                data = '' + ''.join(str(i) for i in line) + '\n'  # 用空格隔开
                outfile.write(data)


if __name__ == "__main__":
    input_file = '1.txt'  # 待读取的文件
    output_file = 'ansi.txt' # 写入的文件
    read_write_txt(input_file, output_file)

待读入文件1.txt

写入后的文件ansi.txt

2.Python读取一个未知编码的文件并将其设置为指定编码格式

要在Python中读取一个未知编码的文件并将其设置为另一种编码格式,可以使用chardet模块来检测文件的编码格式,然后使用Python内置的编码库来进行转换。

使用该代码前需要安装chardet和codecs库

python 复制代码
pip install chardet
pip install codecs

首先,你可以使用chardet模块来检测文件的编码格式。你可以使用以下代码来完成这个步骤:

python 复制代码
# -*- encoding:gb2312 -*-
import chardet
import codecs
def save_as_specified_encoding(input_file, output_file, output_encoding):  #input_file为未知编码文件,output_file为编码后的文件,output_encoding为编码格式
    with open(
            input_file,
            'rb',
    ) as file:     # rb: 以二进制格式打开一个文件用于只读。
        raw_data = file.read()   # 读出内容用到的是read函数。这个函数的工作原理是依靠一个指针来对内容进行访问的。read方法会用一个指针将文本内容从上到下扫面一遍并且将其输出到内存。扫描完后它的指针是停留在末尾处的。也就是说,如果我们想用read方法访问同一个文件两次,是不可行的。
        detected_encoding = chardet.detect(raw_data)['encoding']  # 返回文件的编码格式。

    with codecs.open(input_file,
                     'r',
                     encoding=detected_encoding,
                     errors='ignore') as input_file:
        content = input_file.read()
   # codecs.open(filename, mode='r', encoding=None, errors='strict', buffering=1)  使用给定的 mode 打开已编码的文件并返回一个 StreamReaderWriter的实例,提供透明的编码/解码;与内置函数open类似。

    with codecs.open(output_file,
                     'w',
                     encoding=output_encoding,
                     errors='ignore') as output_file:
        output_file.write(content) 

    if __name__ == "__main__":
    input_file = '1.txt'   # 未知编码文件
    output_file = 'ansi.txt' # 编码后的文件
    output_encoding = 'ansi' # 设置的编码
    save_as_specified_encoding(input_file, output_file, output_encoding)

原始文件1.txt

编码后的文件ansi.txt

3.Python实现txt文件中字符串的替换

python 复制代码
# -*- encoding:gb2312 -*-
def replace_txt(inputpath, outputpath):

    # 打开原始文件和目标文件
    with open(inputpath, 'r') as file:
        content = file.read()

    # 替换字符:和:
    new_content = content.replace(':', ' ')
    new_content = new_content.replace(':', ' ')
    # 将替换后的内容写入目标文件
    with open(outputpath, 'w') as file:
        file.write(new_content)


if __name__ == "__main__":
    input_path = 'ansi.txt'    # 待处理的txt文件
    output_path = 'result.txt'    # 替换字符后的txt文件
    replace_txt(input_path, output_path)

ansi文件(原始文件)

result文件 (替换后的文件)

相关推荐
烛阴7 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼7 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开7 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
2301_805054568 小时前
Python训练营打卡Day59(2025.7.3)
开发语言·python
uncle_ll9 小时前
李宏毅NLP-8-语音模型
人工智能·自然语言处理·语音识别·语音模型·lm
Liudef069 小时前
FLUX.1-Kontext 高效训练 LoRA:释放大语言模型定制化潜能的完整指南
人工智能·语言模型·自然语言处理·ai作画·aigc
万千思绪9 小时前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
微风粼粼10 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
云天徽上10 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
你怎么知道我是队长11 小时前
python-input内置函数
开发语言·python