简体   繁体   中英

How do I read a text file in Pydev?

I'm doing a school assignment that requires me to read a file. I chose to use the Eclipse and Pydev combination because I really like the environment. However, no matter where I place the .txt file I get the following error: FileNotFoundError: [Errno 2] No such file or directory: 'file.txt' I've tried placing it in the src folder and the file directory. Something that I find quite odd is that if I were to run the same python module in IDLE, the file is found and read perfectly. Any help is appreciated!

You should put the file in the same folder as your .py file, if that doesn't work try to find out what directory it's currently using os.getcwd() .

To fix this specifically:

Open Run Dialog...-> Select your run configuration->Arguments Tab->Working directory

EDIT:

import os
print os.getcwd()

If you cannot determine where to place your file - place it anywhere and use absolute path:

print(open(r'c:\your_file.txt', 'r').read())

If you've not played with your eclipse too hard you can just place your_file.txt in your project directory and use:

print(open('your_file.txt', 'r').read())

Update:

From one of your comments I've seen that you are doing sth extremely weird - look here:

在此处输入图片说明

You've somehow managed to open python.exe in your console window within eclipse and you edit files with eclipse but run it from python.exe directly on right hand side hence your code on the left has different environment if executed from eclipse and different when executed from right handside window.

Close that console and push PLAY button in your ECLIPSE: 在此处输入图片说明

You better first edit your files in something easier like notepad++. Just create your python source within directory whrer your python.exe resides and run that from command line with:

python.exe yoursource.py

Once you get a hang of how things work - switch to eclipse. While working in notepad++ follow python tutorial

You simply are trying to do too many unknown to you things at the same time - this way you'll be scratching your head all day long

Pydev in Eclipse default working directory

Took me 10 seconds to find ;)

When you run your script from console it's this file directory, but from eclipse it could be another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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