从其他目录用python打开文本文件时出错

问题描述 投票:0回答:1

代码是

case 'show' | 'display':
      file = open('files/todos.txt','r')
      todos = file.readlines()
      file.close()
      for i,j in enumerate(todos):
          #print(i,"-",j)
          j = j.strip()
          print(f"{i+1}-{j}")

在此输入图片描述

python 的输出是:

Traceback (most recent call last):
  File "C:\Users\kanha\PycharmProjects\pythonProject\venv\main1.py", line 17, in <module>
    file = open('files/todos.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'files/todos.txt'

我想打开位于不同目录中的文件..

python file
1个回答
0
投票

您可以使用文件的完整路径:

“C:\Users\kanha\PycharmProjects\pythonProject iles odos.txt”而不是使用“files/todos.txt”

另一种选择是使用“.. iles odos.txt”作为当前目录的相对路径。

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.