I want to find a.txt file in the directory, and write some text in it. If there are many.txt files, i want to write the same text in all of them. how to do that? python language i need it. 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 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.