读取文件内容时No such file or directory: 'star.txt'

版本:window10 python3.12.4
需求:读取文件 star.txt 中内容
问题:显示 FileNotFoundError: [Errno 2] No such file or directory: ‘star.txt’,已做步骤陈列如下,是哪里出了问题,烦指出
file_name = ‘star.txt’
with open (file_name) as file_object:
lines = file_object.readlines()

Traceback (most recent call last):
File “<pyshell#76>”, line 1, in
with open (file_name) as file_object:
FileNotFoundError: [Errno 2] No such file or directory: ‘star.txt’
补充:已确定拥有读取 star.txt 权限。
在下萌新,望前辈不吝赐教,谢谢!

Jason990420
最佳答案

Check if current working directory, os.getcwd(), to confirm if it is same directory for your star.txt.

>>> import os
>>> os.getcwd()
'C:\\Software\\python\\Lib\\idlelib'

If not, you should add the path to the star.txt file to tell python where to find your file.

file_name = "C:/Users/jjy_0/star.txt"
8个月前 评论
Yvonne_Potter_KafKa1984 (楼主) 7个月前
讨论数量: 5
Jason990420

Check if current working directory, os.getcwd(), to confirm if it is same directory for your star.txt.

>>> import os
>>> os.getcwd()
'C:\\Software\\python\\Lib\\idlelib'

If not, you should add the path to the star.txt file to tell python where to find your file.

file_name = "C:/Users/jjy_0/star.txt"
8个月前 评论
Yvonne_Potter_KafKa1984 (楼主) 7个月前

新手建议把这个去掉

file file

8个月前 评论
Yvonne_Potter_KafKa1984 (楼主) 7个月前

file_name = "C:/Users/jjy_0/censuspopdata.xlsx"

import os os.getcwd () 'C:\Users\jjy_0\AppData\Local\Programs\Python\Python312' file_path = 'C:/Users/jjy_0/censuspopdata.xlsx' # 修正了文件扩展名前的空格,并确保大小写正确

try:
with open (file_path, 'rb') as file: # 使用 'rb' 模式读取二进制文件,如 PDF
content = file.read()
print ("文件内容已读取。") # 处理 content,例如保存到变量或进行其他操作

except FileNotFoundError:
print (f"无法找到文件: {file_path}") import openpyxl wb = openpyxl.load_workbook ('censuspopdata.xlsx') 最后使用了这个,七拼八凑版的,有前边 Jason 的功劳。(>0<)

7个月前 评论