0

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

something text1 pm,bla1,bla1
something text2 pm,bla2,bla2
something text3 am,bla3,bla3
something text4 pm,bla4,bla4

在我想保存的新文件中:

bla1,bla1
bla2,bla2
bla3,bla3
bla4,bla4

我有这个,例如每行的前 10 个字符。我可以改变这个或任何其他想法吗?

with open('example1.txt', 'r') as input_handle:
    with open('example2.txt', 'w') as output_handle:
        for line in input_handle:
            output_handle.write(line[:10] + '\n')
4

5 回答 5

3

这就是该csv模块的用途。

import csv
reader = csv.reader(open('file.csv'))

for row in reader: print(row[1])

然后,您可以使用 shell 将文件的输出重定向到新文件,或者您可以执行以下操作而不是最后一行:

for row in reader:
    with open('out.csv','w+') as f:
        f.write(row[1]+'\n')
于 2013-02-27T20:43:12.917 回答
1

如果格式是固定的:

with open('example1.txt', 'r') as input_handle:
    with open('example2.txt', 'w') as output_handle:
        for line in input_handle:
            if line:  # and maybe some other format check
                od = line.split(',', 1)
                output_handle.write(od[1] + "\n")
于 2013-02-27T20:46:07.073 回答
1

这就是我的写法。

蟒蛇 2.7

import csv
with open('example1.txt', 'rb') as f_in, open('example2.txt', 'wb') as f_out:
    writer = csv.writer(f_out)
    for row in csv.reader(f_in):
        writer.write(row[-2:]) # keeps the last two columns

Python 3.x(注意参数的差异open

import csv
with open('example1.txt', 'r', newline='') as f_in:
    with open('example2.txt', 'w', newline='') as f_out:
        writer = csv.writer(f_out)
        for row in csv.reader(f_in):
           writer.write(row[-2:]) # keeps the last two columns
于 2013-02-27T20:50:05.900 回答
1

要从文件中删除第一个以“,”分隔的列:

first, sep, rest = line.partition(",")
if rest: # don't write lines with less than 2 columns
   output_handle.write(rest)
于 2013-02-27T20:51:05.587 回答
0

尝试:

output_handle.write(line.split(",", 1)[1])

文档

str.split([sep [, maxsplit]])

返回字符串中单词的列表,使用sep作为分隔符字符串。如果给定了maxsplit,则最多完成maxsplit拆分(因此,列表将最多maxsplit+1包含元素)。

于 2013-02-27T20:46:03.890 回答