【问题标题】:python 3.0 "with" syntax error?python 3.0“with”语法错误?
【发布时间】:2013-12-08 16:26:28
【问题描述】:

我的 with 语句有语法错误。我想不通。我正在使用 python 3,每次我使用 with 语句时它都不会拥有它。我正在尝试制作一个 txt 文件的阅读器,我需要这个 with 声明。

import csv

value1 = "Spam"

fname = input(open("Please enter the name of the file you wish to open: ")

with open(fname, 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        if value1 in row:
            print(" ".join(row)) 

我对 python 很陌生,它可能非常明显地为帮助家伙欢呼

【问题讨论】:

  • 旁白:如果你在 Python 3 中打开一个 csv 文件,你应该使用 open(fname, 'r', newline='') 而不是 open(fname, 'rb')(这是你在 Python 2 中的做法。)参见 docs .

标签: python python-3.x syntax with-statement


【解决方案1】:

语法错误不是with引起的,而是print语句引起的。在 Python 3.x 中,print 是一个函数。

>>> print 1
  File "<stdin>", line 1
    print 1
          ^
SyntaxError: invalid syntax
>>> print(1)
1
>>>

所以下面一行:

print " ".join(row) 

应替换为:

print(" ".join(row))

以下句子中缺少括号。

fname = input(open("Please enter the name of the file you wish to open: "))
#                                                                         ^

open 应该省略:

fname = input("Please enter the name of the file you wish to open: ")

【讨论】:

  • @user3077551:请将整个回溯编辑到您的问题中。可能您在前一行有一个未闭合的括号。
猜你喜欢
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多