[英]In Python CSV module while reading and writing how to get rid of apostrophe
[英]How to get rid of [''] when reading .csv files in python
我從一個文件夾中一次打開和讀取一個 .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)
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 模塊,用於讀取和寫入 csv 文件,以防您不知道。
編輯:對不起,我誤讀了你的問題。 將此添加到 readlines 循環的開頭:
line = line.strip()
if not line:
continue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.