0

This is the function for open a file and read the file:

def readFileBytes(
    filePath: Union[Path, str]
) -> bytes:
    if isinstance(filePath, str):
        filePath = Path(filePath)
    fileObject = open(filePath, 'rb')
    rawBytes = fileObject.read()
    fileObject.close()

    print("Path: ", filePath)
    return rawBytes

And the file path that I want to import is:
/Users/zzzz/Desktop/2023/AI/Project/FinalProject/minecraft/villages/common/iron.nbt

And my path file path is :
/Users/zzzz/Desktop/2023/AI/Project/Final Project/minecraft/test_nbt.py

Whether I use:

path = './villages/commom/animals/cat_black.nbt'
nbt = readFileBytes(path)

or

path = '../villages/common/well_bottom.nbt'  # I know it is wrong...
nbt = readFileBytes(path)

It always gives me an error:

    fileObject = open(filePath, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'villages/common/well_bottom.nbt'

But if I use /Users/zzzz/Desktop/2023/AI/Project/Final Project/minecraft/villages/common/iron.nbt, (absolute path) it works.

What is the best/easy way to fix it?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Make sure that the working directory is `/Users/zzzz/Desktop/2023/AI/Project/FinalProject/minecraft` when executing the code. – mkrieger1 Apr 16 '23 at 23:50
  • 1
    Relative paths are relative to the "current working directory" of the program, which is **not necessarily** where the script is. – Karl Knechtel Apr 17 '23 at 00:16
  • 1
    You can add this to your program `import os; print(os.getcwd())` to see what the actual current directory is. – John Gordon Apr 17 '23 at 00:36

0 Answers0