我有一个CSV文件,该文件有时为空,有时其中包含内容。我正在尝试检查CSV是否为空,所以我可以知道是追加还是重新创建。
我已经尝试过:
check_df = pd.read_csv(r'my file')
if check_df.empty:
csvfile = open(r'my file', 'w', newline='')
obj = csv.writer(csvfile)
obj.writerow(["date", "bmo amc", "stock symbol","company name"])
print("csv empty")
else:
csvfile = open(r'my file', 'a', newline='')
obj = csv.writer(csvfile)
print("appending csv")
此代码给我错误:
pandas.errors.EmptyDataError: No columns to parse from file
如果您可以的话,请使用python的新手。
答案 0 :(得分:2)
您应该使用python库而不是pandas检查文件是否为空
在您的情况下,文件为136bytes(如果为空),因此:
import os
if os.path.getsize('my file') < 137:
csvfile = open(r'my file', 'a', newline='')
obj = csv.writer(csvfile)
print("appending csv")
else:
csvfile = open(r'my file', 'w', newline='')
obj = csv.writer(csvfile)
obj.writerow(["date", "bmo amc", "stock symbol","company name"])
print("csv empty")
答案 1 :(得分:0)
您还可以利用python异常处理来避免此错误
import csv
vFileName='tmp.csv'
try:
check_df = pd.read_csv(vFileName)
except:
with open(vFileName, 'w', newline='') as csvfile:
obj = csv.writer(csvfile)
obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
print("csv empty")
else:
with open(vFileName, 'a', newline='') as csvfile:
obj = csv.writer(csvfile)
obj.writerow(["dtest", "bmo amc", "stock symbol","company name"])
print("appending csv")