开发者社区> 问答> 正文

有没有一种方法可以删除txt文件中的空行,然后在python中将其作为csv文件打开

[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

展开
收起
is大龙 2020-03-24 21:33:16 761 0
1 条回答
写回答
取消 提交回答
  • 请检查此。

    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

    2020-03-24 21:33:23
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载