从.txt清除,将新变量写为csv分隔字符串(非列表)到csv文件中

时间:2016-10-08 16:11:37

标签: python csv

我的.txt文件如下所示:

Page 1 of 49
<="">
View Full Profile
S.S. Anne
Oil Tanker
42 miles offshore
Anchor length is 50 feet
<="">
View Full Profile
S.S. Minnow
Passenger Ship
1502.2 miles offshore
Anchor length is 12 feet
<="">
View Full Profile
S.S. Virginia
Passenger Ship
2 km offshore
Anchor length is 25 feet
<="">
View Full Profile
S.S. Chesapeake
Naval Ship
10 miles offshore
Anchor length is 75 feet
<="">

我已经制定了清洁部分,以便在“查看完整档案”之后我接下来的4个项目并将它们放入他们自己的新行项目中,我为“查看完整档案”的每个实例执行此操作。< / p>

代码:

import csv 

data = []
with open('ship.txt','r',encoding='utf8') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if 'View Full Profile' in line:
            x = [lines[i+1],lines[i+2],lines[i+3],lines[i+4]]
            data.append(x)

for line in data:
    y = line
    print(y)

with open('ship_test.csv', 'w') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in data:
        writer.writerow(line)

打印输出y以查看将写入新文件的内容是:

['S.S. Anne\n', 'Oil Tanker\n', '42 miles offshore\n', 'Anchor length is 50 feet\n']
['S.S. Minnow\n', 'Passenger Ship\n', '1502.2 miles offshore\n', 'Anchor length is 12 feet\n']
['S.S. Virginia\n', 'Passenger Ship\n', '2 km offshore\n', 'Anchor length is 25 feet\n']
['S.S. Chesapeake\n', 'Naval Ship\n', '10 miles offshore\n', 'Anchor length is 75 feet\n']
[Finished in 0.1s]

当它复制到新文件中时,我得到以下内容:

"S.S. Anne
","Oil Tanker
","42 miles offshore
","Anchor length is 50 feet
"
"S.S. Minnow
","Passenger Ship
","1502.2 miles offshore
","Anchor length is 12 feet
"
"S.S. Virginia
","Passenger Ship
","2 km offshore
","Anchor length is 25 feet

"
"S.S. Chesapeake
","Naval Ship
","10 miles offshore
","Anchor length is 75 feet
"

我希望将新输出的文件写入y。我相信它会将每个项目写为自己的行,因为附加到x的每个元素的'/ n'。如何删除它(我尝试拆分并收到错误),以便将x作为单个行项目写入新文件中作为csv字符串?

2 个答案:

答案 0 :(得分:0)

line = line.replace('\n', '')

使用替换方法

如果有字符串列表:

line = [l.replace('\n', '') for l in line]

答案 1 :(得分:0)

您应该在阅读该行后立即删除终止换行符。代码的第一部分可能变为:

data = []
with open('ship.txt','r',encoding='utf8') as f:
    for line in lines:
        if 'View Full Profile' in line:
            x = [ next(f).strip(), next(f).strip(),
                  next(f).strip(), next(f).strip() ]
            data.append(x)

您甚至可以动态编写csv文件:

with open('ship.txt','r',encoding='utf8') as f, open('ship_test.csv', 'w') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in f:
        if 'View Full Profile' in line:
            x = [ next(f).strip(), next(f).strip(),
                  next(f).strip(), next(f).strip() ]
            writer.writerow(x)