读取python 3中的文件

2024-03-28 12:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何读取文件,我想知道为什么会发生这种情况,以及如何修复它。我做了一个.txt文件只是为了练习这一点,我在我的文件。当我运行代码时,尽管它告诉我。你知道吗

Errno2 no such file or directory: jub.txt

我也尝试过把它列为C:\Users等等。我看了很多教程。有人能给我解释一下吗?这样我就可以开始工作了。你知道吗

print ("Opening and closing a file")
text_file = open("jub.txt", "r")

print (text_file('jub.txt'))

text_file.close()

Tags: or文件no代码texttxt情况教程
2条回答

为了补充Beri提供的代码,我宁愿使用try/except语句和新样式的字符串格式:

print("Opening and closing a file")
f_name = 'jub.txt'
try:
    with open(f_name, 'r') as text_file:
        print(text_file.read())
except FileNotFoundError:
    print("File {} does not exist".format(f_name))

顺便说一下,我建议您直接阅读官方的Python doc,它非常清晰简洁:

https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files

首先检查您的文件是否存在于当前目录中,您可以添加这个简单的验证。 第二,与包装器一起使用,它将在您退出此块后为您关闭文件。第三:使用read和readlines方法读取文件。你知道吗

print ("Opening and closing a file")
f_name = "jub.txt"
if not os.path.exists(f_name):
  print 'File %s does not exist'%f_name
  return
with open(f_name , "r") as text_file:
   print (text_file.read())

为了使路径更精确,可以使用完整的系统路径,而不是相对路径。示例:'/home/my\u user/doc/myfile.txt文件'

相关问题 更多 >