[英]python, read and write all the file with *.txt extension
如何在循環中讀取和寫入所有擴展名為 *.txt 的文件。 我想將輸出寫入相同的文件名。
我的代碼:
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()
文本1.txt
2 33 /home/workspace/aba/abga
22 4 /home/home
文本2.txt
1 44 /home/workspace/aba/abga
24 5 /home/home
期望的輸出
文本1.txt
/home/workspace/aba/abga
/home/home
文本2.txt
/home/workspace/aba/abga
/home/home
請注意,此目錄中有多個 .txt 文件。 我想遍歷所有這些。
在本例中,我們獲取當前目錄中所有 .txt 文件的列表,將每個文件處理成一個新文件(同名 + .2
),然后刪除原始文件並替換為.2
文件。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.