简体   繁体   中英

How Can You Get a File out from a Directory in Python?

I am declaring a variable in python:

e = ('file.txt', 'r')

But the file is in a directory, and I don't know how to write it so that it will look in my directory playergold. I tried

playergold = 'PlayerFiles/PlayerGold'
e = open('playergold/gold.1.txt', 'r')

and

e = open(from playergold import gold.1.txt', 'r')

and

e = open(playergold/'gold.1.txt', 'r')

but neither works. (btw, I am getting this code from the question Loop Through A Folder in Python )

The directory tree looks like this:

Code contains methods.py, which is where all the code is.

PlayerFiles contains the folder PlayerGold and PlayerItems

PlayerGold contains gold.1.txt

PlayerFiles and Code are on the same level.

Any help would be nice. Thanks for your time!

Looks like you need.

import os

with open(os.path.join('PlayerFiles','PlayerGold', 'gold.1.txt')) as infile:
    data = infile.read()
    #process

确保路径正确并尝试以正确的形式传递它 - 始终记得打开一个封闭的引号。

e = open('playergold/gold.1.txt', 'r')

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