python,以* .txt扩展名读取和写入所有文件

时间:2018-08-21 18:39:23

标签: python loops

如何循环读取和写入所有扩展名为* .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()

text1.txt

2 33 /home/workspace/aba/abga
22 4 /home/home

text2.txt

1 44 /home/workspace/aba/abga
24 5 /home/home

所需的输出

text1.txt

/home/workspace/aba/abga
/home/home

text2.txt

/home/workspace/aba/abga
/home/home

请注意,此目录中有多个.txt文件。我想遍历所有这些。

1 个答案:

答案 0 :(得分:1)

在此示例中,我们获得了当前目录中所有.txt文件的列表,将每个文件处理为一个新文件(名称+ .2),然后删除原始文件并用{{ 1}}文件。

.2
相关问题