简体   繁体   English

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

[英]python, read and write all the file with *.txt extension

How to read and write all the file with *.txt extension in a loop.如何在循环中读取和写入所有扩展名为 *.txt 的文件。 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文本1.txt

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

text2.txt文本2.txt

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

desired output期望的输出

text1.txt文本1.txt

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

text2.txt文本2.txt

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

Please note that there are several .txt files in this directory.请注意,此目录中有多个 .txt 文件。 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.在本例中,我们获取当前目录中所有 .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