使用Python写入目录中的所有*.txt文件

使用Python写入目录中的所有*.txt文件,python,Python,我想根据扩展名写入目录中的所有文件。我可以写入一个特定的文件,但我的目标是编写可以写入特定目录中所有*.txt文件的代码。使用下面的代码,我可以列出所有文本文件并搜索文件,但作为Python初学者,我不知道如何在所有*.txt文件中编写句子 import glob import os directory=os.listdir(r'C:\Users\Lenovo\Desktop\z') myfiles=glob.glob('*.txt') print(myfiles) def find_f

我想根据扩展名写入目录中的所有文件。我可以写入一个特定的文件,但我的目标是编写可以写入特定目录中所有
*.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"))

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

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

这是一个好的开始。我给你一个提示:要能够从文件中读写,你需要使用
open
功能。这里有它的文档。还有一些例子。你能行!有了它,我只能在zineb.txt中编写,但我想在该目录中的所有文件中编写,没问题,伙计;如果有帮助的话,那么你应该在我回答的箭头下面的箭头上打勾,这样人们就知道他们什么时候在看:)