[英]Write in all the *.txt files within a directory using Python
I want to write in all the files within a directory based on their extensions.我想根据扩展名写入目录中的所有文件。 I can write to a specific file but my goal is code that can write to all the
*.txt
files that are in a specific directory.我可以写入特定文件,但我的目标是可以写入特定目录中所有
*.txt
文件的代码。 With the following code I can list all text files and search for a file but as a beginner in Python I don't know how to write a sentence in all the *.txt
files.使用以下代码,我可以列出所有文本文件并搜索文件,但作为 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"))
In your example you should be able to just do the following:在您的示例中,您应该能够执行以下操作:
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.
To do all of them:要做到所有这些:
for textfile in os.listdir():
if textfile.endswith(".txt"):
with open(textfile, "a") as f:
f.write("a")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.