【问题标题】:python syntax error after adding # -*- coding: utf-8 -*-添加# -*- 编码后python语法错误:utf-8 -*-
【发布时间】:2015-10-21 03:32:11
【问题描述】:

我正在准备一个 cvs 文件,

这是我的代码:

import csv
class CsvToJson:
    def __init__(self, csvFilePath):
        with open(csvFilePath, 'rb') as csvFile:
            spamreader = csv.reader(csvFile, delimiter= ‘;’, quotechar = '|')
            for row in spamreader:
                print ', '.join(row)

k = CsvToJson(csvFilePath = 'carsModelsMakes.csv')

我收到了这个错误

SyntaxError: Non-ASCII character '\xe2' in file CsvToJson.py on line 7, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

在第五行。

我在互联网上阅读,似乎解决方案是使用

# -*- coding: utf-8 -*- 

在文件的开头。

我这样做了,但后来我得到了这个错误:

File "CsvToJson.py", line 6
    spamreader = csv.reader(csvFile, delimiter= ‘;’, quotechar = '|')
SyntaxError: invalid syntax

你能帮忙吗

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    这是罪魁祸首:

    delimiter= ‘;’,
    

    您需要直引号,而不是智能引号:

    delimiter= ';',
    

    【讨论】:

    • 现在我收到此错误文件“CsvToJson.py”,第 10 行,在 k = CsvToJson(csvFilePath = 'carsModelsMakes.csv') 文件“CsvToJson.py”,第 7 行,在 init 中用于 spamreader 中的行:_csv.Error: 在未引用的字段中看到换行符 - 您需要以通用换行模式打开文件吗?
    • 我试图在那里检查解决方案,他们说将我的 rb 更改为 rU,但后来我收到一个新错误,即 File "CsvToJson.py", line 5 with open(csvFilePath, 'r ') as csvFile: ^ SyntaxError: EOL while scanning string literal
    • 语法错误:扫描字符串文字时出现 EOL Williams-MacBook-Pro:ExcelToJson williamkinaan$语法错误:扫描字符串文字时 EOL
    • 您必须指明用于创建 CSV 文件的正确方言。如果它是手动创建的,没有特定的方言,您必须手动修复它,遵守特定的方言。 Excel 之类的程序可能会在这方面为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2019-08-16
    相关资源
    最近更新 更多