[英]Python: How to check if cell in CSV file is empty?
我有一個正在用 Python 讀取的 CSV 文件,如果第一列為空,我希望程序跳過該行。 我該怎么做呢?
現在我有:
with open('testdata1.csv', 'rU') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
if row[0] = null:
#?????
我如何:1)檢查 CSV 中的空單元格; 2)告訴讀者跳過這一行?
謝謝你們。
with open('testdata1.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
if not row[0]:
print("12")
您可以使用 try 和 except。
for row in csvreader:
try:
#your code for cells which aren't empty
except:
#your code for empty cells
經過一個小時的嘗試,我能夠做到
while act_tab.cell(row=i, column=1).value is not None:
...
Kit Fung 回答的小改編:
with open('testdata1.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
if not row[0]:
continue # this will skip to the next for loop iteration
# do your processing here
我會假設如果你len()
那么它將為零,即
if not len(row[0])
我嘗試了如果您打印並清空行並返回 [](空括號)會發生什么......所以只需檢查一下。
with open('testdata1.csv', 'rU') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
if row == []:
continue
#do stuff normally
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.