简体   繁体   English

Python在子目录中打开文件-Linux

[英]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()? 是否可以打开文件以在子目录中读取而无需使用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. 我正在/ SCRIPT / PYTHON中运行python脚本,我要调用的文件位于/ SCRIPT / PYTHON / monor-b中。 Any suggestions 有什么建议么

You can use relative paths while opening files in python: 您可以在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. 使用os.path.join比字符串连接或格式化更好的做法,因为它使用正确的路径分隔符和其他特定于OS的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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