首页 > 解决方案 > 使用 Python 写入目录中的所有 *.txt 文件

问题描述

我想根据扩展名写入目录中的所有文件。我可以写入特定文件,但我的目标是可以写入*.txt特定目录中所有文件的代码。使用以下代码,我可以列出所有文本文件并搜索文件,但作为 Python 的初学者,我不知道如何在所有*.txt文件中写一个句子。

import glob
import os
directory=os.listdir(r'C:\Users\Lenovo\Desktop\z')

myfiles=glob.glob('*.txt')
print(myfiles)



def find_files(filename, search_path):
    result= []

    for root, dir, files in os.walk(search_path):
        if filename in files:
            result.append(os.path.join(root, filename))
            return result


print(find_files("zineb.txt",r"C:\Users\Lenovo\Desktop\z"))

标签: python

解决方案


在您的示例中,您应该能够执行以下操作:

textfiles = find_files("zineb.txt",r"C:\Users\Lenovo\Desktop\z")
for textfile in textfiles: # go over each file that it found
    with open(textfile, "a") as f: # open the textfile in mode append (hence the a) and have it be assigned to f
        f.write("a") # then write "a" to the file.

要做到所有这些:

for textfile in os.listdir():
    if textfile.endswith(".txt"):
        with open(textfile, "a") as f:
            f.write("a")

推荐阅读