【问题标题】:Syntax error in print function打印函数中的语法错误
【发布时间】:2013-06-28 19:11:09
【问题描述】:

我从一个将 csv 转换为 xml 的脚本中得到这个

语法错误无效语法

print(text, file=self.file, end=self.args.linebreak)

点在第一个“=”下面。我不确定这是为什么。有人可以指出正确的方向。

谢谢 阿朗佐

class Writer:
def __init__(self, ofile, args):
    self.file = ofile
    self.args = args
    self.newline_subst = field_subst_factory(args.newline_elem)
    if args.header:
        self.fieldname = self.__fieldname_header
    elif args.flat_fields:
        self.fieldname = self.__fieldname_flat
    else:
        self.fieldname = self.__fieldname_indexed
def write_file(self, data):
    if self.args.declaration:
        declaration = ('<?xml version="1.0" encoding="{0}"?>'.
                       format(args.oencoding))
        self.write(declaration)
    self.write("<{0}>".format(self.args.root_elem))
    for record in data:
        self.write_record(record)
    self.write("<\{0}>".format(self.args.root_elem))
def write_record(self, record):
    self.write("{0}<{1}>".
               format(self.args.indent, self.args.record_elem))
    for index, field in enumerate(record):
        self.write_field(field, index)
    self.write("{0}<\{1}>".
               format(self.args.indent, self.args.record_elem))
def write_field(self, field, index):
    self.write("{0}{0}<{1}>{2}</{1}>".
               format(self.args.indent, self.fieldname(index),
                      self.newline_subst(field)))
def write(self, text):
    **print(text, file=self.file, end=self.args.linebreak)** This the line that's causing issues
def __fieldname_header(self, index):
    return self.args.header[index]
def __fieldname_flat(self, index):
    return self.args.field_elem
def __fieldname_indexed(self, index):
    return self.args.field_elem + str(index)

【问题讨论】:

  • 您使用的是哪个版本的 Python?
  • 我使用的是 python 版本 3
  • 那行对我来说编译得很好。这可能是代码中更早的东西的结果,因此发布更多代码会有所帮助。
  • 整个源文件在 Python 3.3.1 中对我来说编译得很好,但在 Python 2.7.4 中由于您提到的错误而失败。你确定你用 3.x 版本运行它吗?文件顶部是否有类似 #!/usr/bin/env python 的 shebang 行导致它在 2.x 版中运行?

标签: python xml csv syntax


【解决方案1】:

如果您使用的是 python 2.x,那么您需要将以下行放在代码的顶部

from __future__ import print_function

【讨论】:

  • 谢谢,但我使用的是版本 3
  • 斯蒂芬,也许我错了,但据我了解,指向第一个“=”的胡萝卜意味着“=”前面的字符是问题所在。还是我误解了 phtyon 文档?
  • self.write("{0}{0}{2}{1}>".format(self.args.indent, self.fieldname(index), self.newline_subst(field))) def write(self, text): print(text, file=self.file, end=self.args.linebreak)
  • 很好,但我尝试加载我的代码,该网站对格式进行了条纹化,并且只是作为一个文本块出现
  • 好了,我想我现在明白了
猜你喜欢
  • 2021-06-24
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
相关资源
最近更新 更多