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

发布于 2025-02-08 22:45:23 字数 295 浏览 2 评论 0原文

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

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

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

Contents of file:

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

I have this basic python script to print out the contents of an entire book I have saved as a text file:

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

But every time I run it, it doesn't actually print out the contents of the book, the output is just:

Contents of file:

What am I doing wrong? I made sure that there is no typo and I am absolutely positive that the text file is saved under the same directory as my program.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终止放荡 2025-02-15 22:45:23

您的代码看起来还不错,因此要消除脚本的活动目录与脚本的实现位置不同的可能性,请将完整路径送入文件。

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

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)

Your code looks okay, so to eliminate the possibility that the active directory of the script is not the same as the script'sactual location, give the full path to the file.

Also, it's safer to open files like this:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文