[Python]我有一个txt文件,其中有一些空行。我想删除这些行并将文件读取为csv
我的txt文件:
Food,Bought
Apple,Yes
Pear,Yes
Starfruit,Yes
Strawberry,No
Lemon,No
Guava,Yes
到目前为止我的代码:
import csv
with open('todo.txt','r+') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
no = 1
for row in csv_reader:
# replacing the answers in the file
if row[1] == 'Yes':
row[1] = "bought"
else:
row[1] = "not bought"
# printing the results
if line_count == 0:
line_count += 1
else:
print(f'{no}: {row[0]} is {row[1]}.')
line_count += 1
no += 1
我想在跑步时看到什么:
1: Apple is bought
2: Pear is bought
3: Starfruit is bought
4: Strawberry is not bought
5: Lemon is not bought
6: Guava is bought
现在,如果我运行它,它将显示一个错误。我尝试先进行剥离,但也显示任何错误。
问题来源:stackoverflow
请检查此。
import csv
with open('test.txt','r+') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
no = 1
for row in csv_reader:
# replacing the answers in the file
if row:
if row[1] == 'Yes':
row[1] = "bought"
else:
row[1] = "not bought"
# printing the results
if line_count == 0:
line_count += 1
else:
print(f'{no}: {row[0]} is {row[1]}.')
line_count += 1
no += 1
或改进的代码。
import csv
with open('test.txt','r+') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_no = 0
for row in csv_reader:
if row:
row[1] = "bought" if row[1] == 'Yes' else "not bought"
if line_no>0:
print(f'{line_no}: {row[0]} is {row[1]}.')
line_no += 1
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。