繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM