【问题标题】:I am trying to write data into file我正在尝试将数据写入文件
【发布时间】:2016-06-20 12:17:31
【问题描述】:

当我运行时我得到错误。为什么 print man 给出错误并且 os.getwd() 也给出错误。但是当我评论说没有错误时。代码按预期工作

from __future__ import print_function;
    import os
    man=[]
    other = []
    print os.getcwd()
    try:
        data = open("sketch.txt")
        for each_line in data:
            try:
                (role,line_spoken) = each_line.split(':',1)
                line_spoken = line_spoken.strip()
                if role=='Man':
                    man.append(line_spoken)
                elif role =='Other Man':
                    other.append(line_spoken)
            except ValueError:
                pass
        data.close()
    except IOError:
        print ("The Data File is Missing")
    print man
    print other
    try:
        man_file = open('man_data.txt','w')
        other_file = open('other_data.txt','w')
        print (man,file = man_file)
        print (other,file = other_file)
        other_file.close()
        man_file.close()
    except IOError:
        pass

【问题讨论】:

    标签: python file save


    【解决方案1】:

    你应该调用print作为函数,因为你导入了print_function

    from __future__ import print_function
    
    print("Hello World")
    

    【讨论】:

    • 我是 python 新手,所以请解释一下如果我评论最后一次尝试部分,那么它工作正常。如果我想打印数据是否在列表中。我会怎么做。跨度>
    • 在python2中print是语句并且不带括号调用,但是在python3中它变成了一个函数并且需要括号。模块__future__ 用于兼容性。
    • 谢谢你.. @Eugene Soldatov
    【解决方案2】:

    据我所知,以下内容。 1)在第一行有一个';'可以删除。 2)第二行'import ...'和底部的其余部分都有应该删除的标签。这些行应该与第 1 行('来自 ...')在同一列中 3)当你使用'print'(正如其他人所说)时,你应该使用'('&')'。 4)为了连贯性,如果函数名和参数之间没有空格(即第 7 行:data = open("sketch...) 然后继续与它们一起使用。对于字符串也是如此,代码可以编译,但最好使用 ' 或 " 不要将它们与代码混合使用。

    期待帮助!

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 2022-12-22
      相关资源
      最近更新 更多