【问题标题】:Python reading file but the command line prints a blank linePython读取文件但命令行打印一个空行
【发布时间】:2015-04-29 13:58:12
【问题描述】:

我正在 Learn Python the Hard Way 并且正在进行练习 16。学习练习说要使用 readargv 编写脚本。

我的代码如下:

from sys import argv

script, file_name, pet_name = argv

print "Ah, your pet's name is %r." %pet_name
print "This will write your pet's name in a text file."
print "First, this will delete the file. "
print "Proceeding..."

writefile = open(file_name, 'w')
writefile.truncate()
writefile.write(pet_name)
writefile.close

raw_input("Now it will read. Press ENTER to continue.")

readfile = open(file_name, "r")
print readfile.read()

代码一直有效。当它说要打印文件时,命令行给出一个空行。

PS C:\Users\[redacted]\lpthw> python ex16study.py pet.txt jumpy
Ah, your pet's name is 'jumpy'.
This will write your pet's name in a text file.
First, this will delete the file.
Proceeding...
Now it will read. Press ENTER to continue.

PS C:\Users\[redacted]\lpthw>

我不确定为什么脚本只是打印一个空白文件。

【问题讨论】:

    标签: python python-2.7 powershell


    【解决方案1】:

    你从来没有调用writefile.close()方法:

    writefile.write(pet_name)
    writefile.close
    #              ^^
    

    在不关闭文件的情况下,有助于加快写入速度的内存缓冲区永远不会被刷新,文件实际上保持为空。

    要么调用方法:

    writefile.write(pet_name)
    writefile.close()
    

    或将该文件用作context manager(使用with statement)让Python 为您关闭它:

    with open(file_name, 'w') as writefile:
        writefile.write(pet_name)
    

    请注意,writefile.truncate() 调用完全是多余的。以写入模式打开文件 ('w') 总是会截断文件已经

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 2020-01-16
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      相关资源
      最近更新 更多