简体   繁体   中英

How do I correctly use the os.path to locate a file stored in a specific folder?

I'm new to python and I've not used os.path that often, but as my projects grew and I started trying to integrate multiple folders together, I realized that it is probably best that I start using the os.path method.

I'm currently trying to get to a json file data.json in a folder (that is within several other folders). I looked at the way it is done online but I think I confused myself.

import os 
import json

x = os.path.join('c:', 'data.json')
data = json.loads(open(x).read())
print(data)

Error message: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Obada\\OneDrive\\Documents\\VS Code Projects\\Basic Chatbot\\data'

I would suggest using os.listdir() method for seeing the existing files in the currently active folder (you can use os.getcwd() ) to see that.

import os 
import json

files = os.listdir()
x = os.path.join('c:', 'data.json')
for i in files:
    if x in files:
        data = json.loads(open(x).read())
        print(data)
    else:
        print("File doesn't exist!")

There are better ways to do this, but I am trying to keep it beginner-friendly as you are new to python.

The path.join() function is for programs that you want to run in diferent os, in this example you dont have to use the join function.

The join function just join the 2 strings with a / or \ depending on the os

In this example its windows so it use \

If its in the c partition you can just use the full (raw) address.

But if the address is relative like this example:

.\example.json

Its depend on the current file or folder that you are in, in this case the python script, you should use the join function

if you are on Windows, you can reach a file in C:\ by using something like this. Note that the second slash is because we need to tell python that it is a \

import os
fullfilename = os.path.join('C:\\', 'data.json')
data = json.loads(open(fullfilename).read())
print(data)

Another useful option is getcwd, which will give you the current directory python is running on.

currdir = os.getcwd()
FILEPATH = os.path.join(currdir,"data.json")

This will ensure that everything is working relative to the directory you are running your code from... no matter where you move the code

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