How to read and write all the file with *.txt extension in a loop. I would like to write output to same file name.
My code:
PWD1 = os.getcwd()
f = open(PWD1+'/' +DirPath + ".txt", "r")
g = open(PWD1+'/' +DirPath + ".txt", "w")
for line in f:
if line.strip():
g.write("\t".join(line.split()[2:]) + "\n") # removes first two columns from text file.
A.close()
f.close()
g.close()
text1.txt
2 33 /home/workspace/aba/abga
22 4 /home/home
text2.txt
1 44 /home/workspace/aba/abga
24 5 /home/home
desired output
text1.txt
/home/workspace/aba/abga
/home/home
text2.txt
/home/workspace/aba/abga
/home/home
Please note that there are several .txt files in this directory. I would like to loop through all of them.
In this example we get a list of all .txt files in the current directory, process each one into a new file (same name + .2
), and then delete the original and replace it with the .2
file.
import glob
files = glob.glob('*.txt')
for f in files:
with open(f, 'rt') as reader:
with open(f+'.2', 'wt') as writer:
for line in reader:
writer.write("\t".join(line.split()[2:]) + "\n") #your logic not mine
os.remove(f)
os.rename(f+'.2', f)
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.