【发布时间】:2023-02-23 03:20:21
【问题描述】:
我在使用 Python 打开 .txt 文件时遇到问题。我的 .txt 文件和脚本都在桌面上的同一个文件夹中,但是在尝试打开文件 Random.txt 时收到“找不到文件”错误。如果我提供完整路径,该文件将打开,这是我试图避免的。
with open('Random.txt', 'r') as file:
contents = file.read()
print(contents)
我注意到,当我尝试以下代码时,它指定文件和脚本位于不同的目录中。
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
file_path = 'Random.txt'
file_dir = os.path.dirname(os.path.realpath(file_path))
if script_dir == file_dir:
print('The script and Random.txt file are in the same directory.')
else:
print('The script and Random.txt file are in different directories.')
print()
print(script_dir)
print(file_dir)
为什么我在尝试仅使用文件名 (Random.txt) 而不是使用完整路径时收到此错误。在我的文件夹中查看这两个项目的属性时,它们具有相同的路径。我使用的是 Windows 设备、VSC 和 Python 3.11.2
【问题讨论】: