简体   繁体   English

从文件夹读取 file.txt 到其他文件夹会出错

[英]Reading file .txt from folder to other folder give error

Hello Guys this is my project tree:大家好,这是我的项目树:

C:.
├───data
│   └───path
│           name.txt
│
└───Resources
        get.py

I need to read text from name.txt file.我需要从 name.txt 文件中读取文本。

I add this code in get.py :我在get.py中添加了这段代码:

class path():

    with open('data/path/name.txt', 'r') as file:
        path = file.readline()
        print(path)

this not working I see this message error:这不起作用我看到此消息错误:

Traceback (most recent call last):
  File "C:\Users\JOHN\Desktop\New folder\Resources\get.py", line 1, in <module>
    class path():
  File "C:\Users\JOHN\Desktop\New folder\Resources\get.py", line 3, in path
    with open('data/path/name.txt', 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'data/path/name.txt'

If you start the filepath with a name, it will continue from the working directory (the directory of the python file if you're running in IDLE).如果您以名称启动文件路径,它将从工作目录(如果您在 IDLE 中运行,则为 python 文件的目录)继续。

If you want to specify an absolute path on windows, add C:/ to the beginning, so with your example:如果要在 windows 上指定绝对路径,请将C:/添加到开头,以您的示例为例:

open('C:/data/path/name.txt', 'r')

Try with the full path C:/data/path/name.txt or relative ../data/path/name.txt .尝试使用完整路径C:/data/path/name.txt或相对../data/path/name.txt

To use a relative path (as you're doing now), you need to modify your relative path so that it begins one level up.要使用相对路径(就像您现在所做的那样),您需要修改相对路径,以便它从上一级开始。 Try this:尝试这个:

open('../data/path/name.txt', 'r')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM