python,读写所有扩展名为*.txt的文件

2024-10-01 00:15:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在循环中读写扩展名为*.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文件。我想把它们都循环一遍。你知道吗


Tags: 文件代码文本txthomecloseos文件名