繁体   English   中英

如何在python中正确打开文件并打印出文本内容

[英]How to properly open a file in python and have the text contents printed out

我正在尝试打开一个名为sun_og.text的现有文件。 以下是我的代码。 我想要在文件中写入的内容在我的终端中打印出来。

f = open("sun_og.txt", "r")
file_contents = f.read()
print (file_contents)
file.close()

但我不断收到此错误消息

FileNotFoundError: [Errno 2] No such file or directory: 'sun_og.txt'

您的脚本可能与文本文件不在同一目录中,这就是引发此错误的原因。

要解决此问题,请尝试提供绝对/相对文件路径。

此外, 在处理文件时,最好使用with因为它会自动为您关闭文件。

试试这个:

with open("your_path/sun_og.txt", "r") as f:
    file_contents = f.read() ## You only need this line if you're going to use the file contents elsewhere in the code
    print(file_contents) ## Otherwise, you could remove the line above and replace this line with print(f.read())

或者,您可以使用os模块,因为您可以使用其chdir函数重定位到另一个目录 (在本例中,是文本文件的目录)。 有关更多信息,请参阅@ Jones1200的答案。

您可以使用os模块转到文本文件所在的目录。

import os

directory_of_text = r'Your/Directory/with/text_file'
os.chdir(directory_of_text)

之后使用你的代码,它应该工作。

暂无
暂无

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

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