从每个lin中删除特定文本

2024-04-19 21:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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')

Tags: 文件txtinputoutputaswithlineopen
3条回答

要从文件中删除以“,”分隔的第一列,请执行以下操作:

first, sep, rest = line.partition(",")
if rest: # don't write lines with less than 2 columns
   output_handle.write(rest)

如果格式是固定的:

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")

这就是^{}模块的用途。你知道吗

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')

相关问题 更多 >