如何摆脱[“”]在Python
我打开和在同一时间从文件夹中读取一个.csv文件并打印出来如下阅读的.csv文件时:如何摆脱[“”]在Python
ownerfiles = os.listdir(filepath)
for ownerfile in ownerfiles:
if ownerfile.endswith(".csv"):
eachfile = (filepath + ownerfile) #loops over each file in ownerfiles
with open (eachfile, 'r', encoding="UTF-8") as input_file:
next(input_file)
print(eachfile)
for idx, line in enumerate(input_file.readlines()) :
line = line.strip().split(",")
print(line)
然而,当我做print(line)
文件打印如下:
/Users/Sulz/Desktop/MSBA/Applied Data Analytics/Test_File/ownerfile_138.csv
['']
['2010-01-01 11:28:35', '16', '54', '59', '0000000040400', 'O.Coffee Hot Small', 'I', ' ', ' ', '14', '1', '0', '0.3241', '1.4900', '1.4900', '1.4900', '0.0000', '1', '0', '0', '0', '0.0000', '0.0000', '1', '44', '0', '0.00000000', '1', '0', '0', '0.0000', '0', '0', '', '0', '5', '0', '0', '0', '0', 'NULL', '0', 'NULL', '', '0', '20436', '1', '0', '0', '1']
我怎样才能摆脱['']
在所有数据列表之前?
编辑:
我现在试图与该.csv模块这样阅读它:
ownerfiles = os.listdir(filepath)
for ownerfile in ownerfiles:
if ownerfile.endswith(".csv"):
eachfile = (filepath + ownerfile) #loops over each file in ownerfiles
with open (eachfile, 'r', encoding="UTF-8") as input_file:
next(input_file)
reader = csv.reader(input_file, delimiter=',', quotechar='|')
for row in reader :
print(row)
但是,它仍然打印输出是这样的:
[] ['2010 -01-01 11:28:35','16','54','59','0000000040400','O.Coffee Hot Small','I','','','14',' 1' , '0', '0.3241', '1.4900', '1.4900', '1.4900', '0.0000', '1', '0', '0', '0', '0.0000', '0.0000' ,'1','44','0','0.00000000','1','0','0','0.0000', '0','0','','0','5','0','0','0','0','NULL','0','NULL','', '0','20436','1','0','0','1']
这只是Python的列表语法正在打印。您正在分割每个生成列表的逗号。如果您在拆分之前打印的行,你可能会得到你在找什么:
line = line.strip()
print(line)
line = line.split(",")
顺便说一下,Python有用于读取和写入的CSV文件built in CSV module,如果你不知道。
编辑:对不起,我误解你的问题。添加到您的readlines循环的开始:
line = line.strip()
if not line:
continue
对不起,我不清楚我在问什么!我的意思是我怎样才能摆脱在实际数据输出之前列出的那个小空列表[['']'? –
您应该使用['csv'(https://docs.python.org/3/library/csv.html#csv.reader)模块中的标准库读取的CSV文件 – 2017-10-29 02:14:48
以及它依赖于数据你的文件,你可以请添加你的文件中的数据的例子。 – scharette