octain
octain

Reputation: 964

Python open a file in a subdirectory - linux

Is it possible to open a file for reading in a sub directory without having to use os.listdir()? Something like this maybe?

f1 = open('/SCRIPT/PYTHON/monomer-b/{}'.format(xyzfile)).read()

I am running the python script in /SCRIPT/PYTHON the files that I want to call is in /SCRIPT/PYTHON/monor-b. Any suggestions

Upvotes: 1

Views: 12070

Answers (1)

kammala
kammala

Reputation: 427

You can use relative paths while opening files in python:

import os  
file_content = open(os.path.join('./monomer-b', xyzfile)).read()

Also, by default all paths looks up starting at current directory, so the './' part of subdir name is not necessary. Using os.path.join is better practice than string concatenation or formatting, because it use correct path separators and another OS-specific things.

Upvotes: 4

Related Questions