Python - 对试图理解的人的基本解释(CSV,Excel)

标签 python excel csv syntax-error

我已经逐行浏览了这段代码并解释了每个步骤。然而,由于我对 python 非常陌生(就像这是我第一次使用它),我很困惑这个函数正在做什么/为什么我收到错误消息。任何帮助将不胜感激!

print("Exercise 2 begins")
import csv  
c = 0       
t = 0      

with open('adele.csv','r') as csvfile:
    csvdata = csv.reader(csvfile, delimiter='\t')  
for line in csvdata:  
    t = t + 1         
    try:
        if 'grammy' in line[5]:  
            c = c + 1            
            print(c + ": " + t + ": " + str(line[5]))   # (7) Describe the purpose of this line
    except IndexError:           
        pass                    

csvfile.close()
print("Exercise 2 ends\n")

最佳答案

错误消息是代码应在 for line in csvdata: 之后缩进。

print("Exercise 2 begins")

import csv  # Include csv package to allow processing of csv files
c = 0       # Initialize a variable "c" with value "0"
t = 0       # Initialize a variable "t" with value "0"

# (1)  You will run into an error when running this code. 
#      What is the error message? 
#      What does the message mean and how do you fix it?

with open('adele.csv','rb') as csvfile:
    csvdata = csv.reader(csvfile, delimiter='\t') # (2) What does this line mean
    for line in csvdata:                          # (3) What does this line mean
        t = t + 1         # (4) Describe the purpose of this line
        try:
            if 'grammy' in line[5]:  # (5) What does this line mean and 
                                     # what is in line[5]
                c = c + 1            # (6) What does this line mean
                print(c + ": " + t + ": " + str(line[5])) # (7) What does this line mean
        except IndexError:           
            pass

根据 adele.csv,此代码可能有效,也可能无效。尝试一下,并尝试了解它的作用和作用。没有错误信息,会更容易理解。

这段代码可能会检查阿黛尔获得的格莱美奖的数量,但如果没有看到 adele.csv,就很难说。

关于Python - 对试图理解的人的基本解释(CSV,Excel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535107/

相关文章:

python - Frida python 将输出重定向到文件

python - 在python中将列表打印为不带括号或逗号的字符串

python - (扩展)用户表格

excel - 如何使用宏复制每一行

python - CSV文件和python中的控制字符

python - 在 MacOS 上使用 PyInstaller 加载 Python 库时出错

Excel - 记录客户购买的商品数量

vba - 如何在 Excel VBA 用户窗体中创建两列查找组合框

python - 将 csv 转换为 JSON 树结构?

csv - 在 Vim 中隐藏给定字符之后的部分行