我对Python很新,所以如果这很明显我很抱歉,但我的代码很简单,所以我不明白它出错的地方。我正在使用csv模块读取一个文件,其中包含来自两个不同来源(L和R)的信息并将其拆分为两个新文件。问题是,当它创建新文件时,它会将它们创建为.txt文件,这是我以前从未见过的csv文件。
import csv
with open('dataset1.csv') as csvfile:
filein = csv.reader(csvfile)
with open('dataset1Left', 'w', newline = '') as fixleft:
fixleftwriter = csv.writer(fixleft)
with open('dataset1Right', 'w', newline = '') as fixright:
fixrightwriter = csv.writer(fixright)
for row in filein:
if (row[2] == 'L'):
fixleftwriter.writerows([row])
elif (row[2] == 'R'):
fixrightwriter.writerows([row])
csvfile.close()
答案 0 :(得分:0)
试试这个:
import csv
with open('dataset1.csv') as csvfile:
filein = csv.reader(csvfile)
with open('dataset1Left.csv', 'w', newline = '') as fixleft:
fixleftwriter = csv.writer(fixleft)
with open('dataset1Right.csv', 'w', newline = '') as fixright:
fixrightwriter = csv.writer(fixright)
for row in filein:
if (row[2] == 'L'):
fixleftwriter.writerows([row])
elif (row[2] == 'R'):
fixrightwriter.writerows([row])
csvfile.close()
简而言之,将.csv
扩展名添加到文件名。
答案 1 :(得分:0)
import csv
with open('dataset1.csv') as csvfile:
filein = csv.reader(csvfile)
with open('dataset1Left.CSV', 'w', newline = '') as fixleft:
fixleftwriter = csv.writer(fixleft)
with open('dataset1Right.CSV', 'w', newline = '') as fixright:
fixrightwriter = csv.writer(fixright)
for row in filein:
if (row[2] == 'L'):
fixleftwriter.writerows([row])
elif (row[2] == 'R'):
fixrightwriter.writerows([row])
csvfile.close()
答案 2 :(得分:0)
您没有提供文件扩展名:
with open('dataset1Left', 'w', newline = '') as fixleft:
...
with open('dataset1Right', 'w', newline = '') as fixright:
这两者都需要文件扩展名才能获得.csv
扩展名:
with open('dataset1Left.csv', 'w', newline = '') as fixleft:
^^^^ This is needed
...
with open('dataset1Right.csv', 'w', newline = '') as fixright:
^^^^ This is needed
答案 3 :(得分:0)
而不是with open('dataset1Left', 'w', newline = '')
尝试将扩展名添加到文件中:
with open('dataset1Left.csv', 'w', newline = '')
喜欢这个
答案 4 :(得分:0)
由于你是python的新手,你可能不知道pandas是处理csv文件的最佳选择。为了做同样的事情,pandas中的代码将是
import pandas as pd
a = pd.read_csv('dataset1.csv',header=None)
a[a[2]=='L'].to_csv('dataset1left.csv',index=False,header=False)
a[a[2]=='R'].to_csv('dataset1right.csv',index=False,header=False)
我不喜欢这个解决方案的唯一原因是,如果你的文件太大,可用的内存耗尽。