繁体   English   中英

Python:通过循环编辑一系列txt文件

[英]Python: editing a series of txt files via loop

使用 Python 我试图编辑一系列文本文件以插入一系列字符串。 我可以用一个 txt 文件成功地做到这一点。 这是我的工作代码,它在 txt 文件中的主体前后附加消息:

filenames = ['text_0.txt']

with open("text_0.txt", "w") as outfile:
    for filename in filenames:
        with open(filename) as infile:
            header1 = "Message 1:"
            lines = "\n\n\n\n"
            header2 = "Message 2:"
            contents = header1 + infile.read() + lines + header2
            outfile.write(contents)

我正在寻求一些帮助来构建脚本以迭代地对目录中的一系列类似 txt 文件进行相同的编辑。 有 20 个或类似的 txt 文件的结构相同: text_0.txttext_1.txttext_2.txt等。 非常感谢任何帮助。

要循环浏览文本文件的文件夹,您需要这样做:

import os


YOURDIRECTORY = "TextFilesAreHere" ##this is the folder where there's your text files

for file in os.listdir(YOURDIRECTORY):
    filename = os.fsdecode(file)
    with open(YOURDIRECTORY  + "/" + filename, "r"):
        ###do what you want with the file

如果您已经知道文件命名,那么您可以简单地循环:

filenames = [f'text_{index}.txt' for index in range(21)]

for file_name in filenames:
    with open(file_name, "w") as outfile:
    for filename in filenames:
        with open(filename) as infile:
            header1 = "Message 1:"
            lines = "\n\n\n\n"
            header2 = "Message 2:"
            contents = header1 + infile.read() + lines + header2
            outfile.write(contents)

或循环目录,如:

import os

for filename in os.listdir(directory):
      #do something , like check the filename in list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM