如何读取/写入多个文本文件

发布于 2025-01-10 01:36:48 字数 624 浏览 1 评论 0原文

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

在此处输入图像描述

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

<图片src="https://i.sstatic.net/dTomu.png" alt="在此处输入图像描述">

我想遍历每个文件并输入文本 This is file #i 在某一行,其中 i 是文件名中文件的确切编号。我已经看过无数关于 os 模块的视频,但仍然无法弄清楚。

因此仅供参考,

在此处输入图像描述

是我尝试为目录中的每个文件实现的目标。

So in short, i have a directory that looks like

enter image description here

All the given text files look like

enter image description here

and I want to iterate through each file and input the text This is file #i at a certain line where i is the EXACT number of the file in its file name. I've watched countless videos on the os module, but still cant figure it out.

So just for reference,

enter image description here

is the goal im trying to reach for each file within the directory.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌面超妹 2025-01-17 01:36:49

我会这样做:

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

I would do it like this:

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))

You can have indirpath and outdirpath as the same if your goal is to overwrite the original files.

拧巴小姐 2025-01-17 01:36:49

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

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

You can use a simple approach of reading the lines, modifying them and writing back. This is good enough if your files are not very large.
An eg.

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
尛丟丟 2025-01-17 01:36:49
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))
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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文