[英]how to find .txt files in a directory, and write in it in python?
I want to find a.txt file in the directory, and write some text in it.我想在目录中找到一个.txt 文件,并在其中写入一些文本。 If there are many.txt files, i want to write the same text in all of them.
如果有很多.txt 文件,我想在所有文件中写入相同的文本。 how to do that?
怎么做? python language i need it.
python 语言我需要它。 Is there any way i can do this?
有什么办法可以做到这一点?
for file in os.listdir("/Users/coder/Desktop/Sample Folder"):
if file.endswith(".txt"):
print(os.path.join("/Users/coder/Desktop/Sample Folder", file))
x = open(file, "r+")
x.write("This file is a .txt file")
You can shift the lines in the for loop.您可以移动 for 循环中的行。
for file in os.listdir("/Users/coder/Desktop/Sample Folder"):
if file.endswith(".txt"):
with open(os.path.join("/Users/coder/Desktop/Sample Folder", file),"a+") as file:
file.write("This file is a .txt file")
You can enter data like this,你可以这样输入数据,
import glob
import os
path = 'E:\Path'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'a') as f:
f.write("Type the required information")
Change the path
to the folder you are changing the text of更改要更改其文本的文件夹的
path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.