python 读取文件执行不了

with open(‘pi_digits.txt’) as file_object:

contents=file_object.read()
print(contents)

python读取文件执行不了

python读取文件执行不了

讨论数量: 4
Jason990420

请修改代码, 测试一下

import os
...
# 确认目录所在为你的 python_work
print(os.getcwd())

# 要检查的档案路径
filepath = 'pi_digits.txt'

# 检查档案是否存在
if os.path.isfile(filepath):
  print("档案存在。")
else:
  print("档案不存在。")

with open(filepath) as file_object:
    contents=file_object.read()

print(contents)
...
3年前 评论
wangyawei_1990 (楼主) 3年前

file你好,还是显示文档不存在

3年前 评论
Jason990420 3年前
Jason990420

你没搞对重点, 截屏中没重要内容, 而且没有你的相关代码

c:\Users\as\Destop\python_work> dir                     <== 少了這个
..
aa.py
pi_digits.txt
..

c:\Users\as\Destop\python_work> python aa.py            <=== 还有這个
c:\Users\as\Destop\python_work
档案不存在.
Traceback (most recent call last):
  File "aa.py", line 16, in <module>
    with opne(filepath) as file_object:
FileNotFoundError: [Error 2] No such file or directory: 'pi_digits.txt'
请按任意键继续...

c:\Users\as\Destop\python_work> type aa.py
...
3年前 评论

相对路径不正确,可以参考在操作系统下的的相对路径表示法

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!