【问题标题】:Keep gettting an error with this simple python exercise这个简单的python练习不断出错
【发布时间】:2021-05-23 09:53:47
【问题描述】:

我需要将此列表写入文件并输出名称,每个名称都换行。

我试试:

names = ["John", "Oscar", "Jacob"]

file = open("names.txt", 'w+')

with file as f:
    f.write("%s\n" % i for i in names)

file.close()

file = open('names.txt', 'r')

print(file)

file.close()

我得到:

TypeError: write() argument must be str, not generator

我也试过了:

names = ["John", "Oscar", "Jacob"]

file = open("names.txt", 'w+')

for i in names:
    file.write(i + '\n')

file.close()

file = open('names.txt', 'r')

print(file)

file.close()

我得到:

<_io.TextIOWrapper name='names.txt' mode='r' encoding='cp1252'>

我使用 Windows Powershell 和手机上的 SoloLearn 应用进行了尝试。我做错了什么?!

【问题讨论】:

  • 第二种方法是正确的。唯一的问题是您打印的是文件对象而不是其内容。试试print(file.read()) 而不是print(file)

标签: python list file writing


【解决方案1】:

试试这个:

names = ["John", "Oscar", "Jacob"]
with open("names.txt", "w+") as file:
    for i in names:
        file.write(i + "\n")

with open("names.txt", "r") as file:
    data = file.read().splitlines()

print(data)

总的来说,我喜欢使用 with 语句,因为您不必关闭文件并防止错误

【讨论】:

    【解决方案2】:
    names = ["John", "Oscar", "Jacob"]
    
    file = open("names.txt", 'w+')
    
    with file as f:
        f.write("\n".join(names))
    
    file.close()
    
    file = open('names.txt', 'r')
    
    print(file.read())
    
    file.close()
    

    【讨论】:

      【解决方案3】:

      "%s\n" % i for i in names) 创建生成器,但 f.write() 需要 str。您可以使用 join 将其转换为字符串

      f.write('\n'.join("%s" % i for i in names))
      

      您也不需要打开文件两次来写入它,在写入/读取完成后使用with打开和关闭它

      with open("names.txt", 'w+') as f:
          f.write('\n'.join("%s" % i for i in names))
      
      with open('names.txt', 'r') as f:
          print('\n'.join(name.strip() for name in f.readlines()))
      

      【讨论】:

      • 这个解决方案还是给了我:<_io.textiowrapper name="names.txt" mode="r" encoding="cp1252">
      • 更新的答案在 txt 文件中有效。但在 powershell 中,这些名称并不都在一个新行上。
      • @snoopaloop 要在新行中打印每个名称,您可以使用print('\n'.join(name.strip() for name in f.readlines()))
      • 生成器生成字符串时,write方法怎么会拒绝生成器?
      • @snoopaloop 它仍然是一个 Generator 对象,而不是一个字符串。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2022-11-21
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2020-09-24
      相关资源
      最近更新 更多