【问题标题】:Issues with opening files using Python使用 Python 打开文件的问题
【发布时间】: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

【问题讨论】:

    标签: python file


    【解决方案1】:

    语法:

    with open('Random.txt', 'r') as file:
    

    将仅在与 Python 脚本相同的文件夹中查找该文件。这是最合理的做法,因为在整个计算机中搜索太慢了。

    您必须将文件放在与脚本相同的目录中或使用完整路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2012-04-19
      • 2013-05-18
      • 2020-01-22
      • 1970-01-01
      • 2018-08-15
      相关资源
      最近更新 更多