gpt4 book ai didi

python - Python读取文件,但命令行打印空白行

转载 作者:行者123 更新时间:2023-12-03 01:16:20 28 4
gpt4 key购买 nike

我正在艰苦学习Python,并且正在练习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>

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

最佳答案

您从未调用过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')打开文件总是会截断该文件。

关于python - Python读取文件,但命令行打印空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755193/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com