如何 read/write 到多个文本文件

How to read/write to many text files

简而言之,我有一个看起来像

的目录

所有给定的文本文件看起来都像

我想遍历每个文件并在特定行输入文本 This is file #i,其中 i 是文件名中文件的确切编号。我在os模块上看了无数视频,但还是想不通。

所以仅供参考,

我试图为目录中的每个文件达到的目标。

我会这样做:

indirpath = 'path/to/indir/'
outdirpath = 'path/to/outdir/'
files = os.listdir(indirpath)
inp_pos = 2 # 0 indexed line number where you want to insert your text

for file in files:
    name = os.path.splitext(file)[0]     # get file name by removing extension
    inp_line = f'This is file #{name}'    # this is the line you have to input
    lines = open(os.path.join(indirpath, file)).read().strip().split('\n')
    lines.insert(min(inp_pos, len(lines)), inp_line) # insert inp_line at required position

    with open(os.path.join(outdirpath, file), 'w') as outfile:
        outfile.write('\n'.join(lines))

如果您的目标是覆盖原始文件,您可以让 indirpathoutdirpath 相同。

您可以使用一种简单的方法来读取行、修改它们并写回。如果您的文件不是很大,这就足够了。 一个例子

def process_file(file, insert_index):
    file_lines = []
    # read the lines in file
    with open(file, "r") as f:
        file_lines = f.readlines()

    # insert the new line and write back to file
    with open(file, "w") as f:
        file_lines.insert(insert_index, f"This is file #{file.stem}\n")
        f.writelines(file_lines)


if __name__ == '__main__':
    from glob import glob
    import pathlib

    files = glob('./test/*.txt')  # list your files in the folder
    [process_file(pathlib.Path(file), 2) for file in files]  # Update each file in the list
import os
folder_path = "you_folder"
row_you_expected_to_insert = 2

for file_name in os.listdir(folder_path):
    front_part = ""
    after_part = ""
    with open(os.path.join(folder_path, file_name), "r+") as f:
        for i in range(1,row_you_expected_to_insert):
            # read until the place you want to insert
            front_part += f.readline()
        after_part = f.readlines()
        f.seek(0)
        f.write(front_part)
        f.write(f"This is file #{file_name.split('.')[-2]}\n")
        f.write("".join(after_part))