Python:如何为每行文本文件

时间:2017-03-02 21:39:30

标签: python

我有一个这种格式的文本文件:

1   1  (101):  3.7e+08  1.2e+02  5.1234
2   1  (101):  3.5e+08  8.2e+02  6.2222
2   2  (101):  1.7e+08  2.2e+02  7.4567
3   1  (101):  8.7e+08  3.2e+02  9.2123

我想把它变成以下格式:

1   3.7e+08  1.2e+02  5.1234
2   3.5e+08  8.2e+02  6.2222
2   1.7e+08  2.2e+02  7.4567
3   8.7e+08  3.2e+02  9.2123

我基本上试图从每一行删除第二个和第三个元素/变量。有什么建议?我是python的新手,不确定如何处理这个问题。任何帮助,将不胜感激。感谢

代码正在进行中。 到目前为止,它读取file.txt并删除前三行并将其写为newfile.txt。这是:

import sys
try:
     f=open('file.txt', 'r')
     lines = f.readlines()
except IOError:
     print('File file.txt does not exist')
     sys.exit(1)
for line in lines:
     sys.stdout.write(line)
     f.close()
# Deleting the first three lines
del lines[0:3]
# Deleting the second and third element of every line

f=open('newfile.txt','w')
f.writelines(lines)
print(lines)
f.close()

2 个答案:

答案 0 :(得分:0)

这可能是通过使用csv阅读文件来完成的。看来文件是制表符分隔的(请确认?),所以你可以通过

来完成
import csv

with open('file.txt', 'rb') as f:
    reader = csv.reader(f, delimiter='\t') # Adjust delimiter as appropriate to your file format.

    # Skip 3 lines.
    for i in xrange(3):
         reader.next()

    new_lines = []
    for line in reader:
         new_line = [line[0]] + line[3:]
         new_lines.append(new_line)

# Write to the new file
with open('new_file.txt', 'wb') as f:
    writer = csv.writer(f, delimiter='\t') # Again, adjust delimiter as appropriate.
    writer.writerows(new_lines)

答案 1 :(得分:0)

这也许就是你要找的。

import sys
try:
     f=open('file.txt', 'r')
     lines = f.readlines()
except IOError:
     print('File file.txt does not exist')
     sys.exit(1)

for line in lines:
     sys.stdout.write(line)
     f.close()

newl=[]
for line in lines:
    temp = line.split()
    newl.append([temp[0]]+temp[3:])

f=open('newfile.txt','w')
f.writelines(['  '.join(l)+'\n' for l in newl])
print(newl)
f.close()