繁体   English   中英

为什么我的脚本不打印文件的内容?

[英]Why doesn't my script printing the contents of my file?

我有这个基本的 python 脚本可以打印出我保存为文本文件的整本书的内容:

f = open("pride.txt", "r", encoding="UTF-8")
s = f.read()
f.close()
print("Contents of file:", s)

但是每次我运行它时,它实际上并没有打印出书的内容,输出只是:

Contents of file:

我究竟做错了什么? 我确保没有错字,并且我绝对肯定文本文件保存在与我的程序相同的目录下。

您的代码看起来不错,因此为了消除脚本的活动目录与脚本的实际位置不同的可能性,请提供文件的完整路径

此外,打开这样的文件更安全:

path = "/full/path/to/the/file/pride.txt"
with open(path, "rt", encoding="UTF-8") as f:
    s = f.read()

print("Contents of file:", s)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM