python 코드가 이전 windows 디렉토리 ‘main’에 의해 알려지지 않고 실행되고 코드가 실행될 때 설치되는 모든 위치에서 ‘main / 2091 / data.txt’디렉토리에 액세스해야한다고 가정하십시오.
open (location) 기능을 어떻게 사용해야합니까? 위치는 무엇입니까?
편집하다 :
아래의 간단한 코드가 작동한다는 것을 알았습니다. 단점이 있습니까?
file="\2091\sample.txt"
path=os.getcwd()+file
fp=open(path,'r+');
답변
이 유형의 작업으로 실제 작업 디렉토리가 무엇인지주의해야합니다. 예를 들어, 파일이있는 디렉토리에서 스크립트를 실행할 수 없습니다.이 경우 상대 경로 만 사용할 수는 없습니다.
원하는 파일이 스크립트가 실제로 위치한 하위 디렉토리에 있다고 확신하면 __file__
여기에서 도움을 줄 수 있습니다. __file__
실행중인 스크립트가있는 전체 경로입니다.
따라서 다음과 같이 바이올린을 칠 수 있습니다.
import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
답변
이 코드는 잘 작동합니다.
import os
def readFile(filename):
filehandle = open(filename)
print filehandle.read()
filehandle.close()
fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir
#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)
#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)
#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)
#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)
답변
Russ의 원래 답변에서 찾은 불일치를 명확히 할 수 있도록 계정을 만들었습니다.
참고로 그의 원래 답변은 다음과 같습니다.
import os
script_dir = os.path.dirname(__file__)
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
원하는 파일에 대한 절대 시스템 경로를 동적으로 만들려고하므로 큰 대답입니다.
Cory Mawhorter __file__
는 상대 경로 (내 시스템에도 있음)를 발견하고을 사용하도록 제안했습니다 os.path.abspath(__file__)
. os.path.abspath
그러나, 현재 스크립트의 절대 경로를 반환 (예 /path/to/dir/foobar.py
)
이 방법을 사용하려면 (그리고 결국 어떻게 작동하는지) 경로 끝에서 스크립트 이름을 제거해야합니다.
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
결과 abs_file_path (이 예에서)는 다음과 같습니다. /path/to/dir/2091/data.txt
답변
사용중인 운영 체제에 따라 다릅니다. Windows와 * nix 모두와 호환되는 솔루션을 원한다면 다음과 같습니다.
from os import path
file_path = path.relpath("2091/data.txt")
with open(file_path) as f:
<do stuff>
잘 작동합니다.
이 path
모듈은 운영 체제에 관계없이 경로를 포맷 할 수 있습니다. 또한 파이썬은 올바른 권한이있는 한 상대 경로를 잘 처리합니다.
편집 :
의견에서 kindall이 언급했듯이, 파이썬은 어쨌든 유닉스 스타일과 윈도우 스타일 경로를 변환 할 수 있으므로 간단한 코드조차도 작동합니다.
with open("2091/data/txt") as f:
<do stuff>
즉, path
모듈 에는 여전히 유용한 기능이 있습니다.
답변
Windows 시스템에서 코드가 Python 3을 실행하는 파일을 찾을 수없는 이유를 찾기 위해 많은 시간을 소비합니다. 그래서 나는 추가했다. 이전과 모든 것이 잘 작동했습니다.
import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
print(file_path)
fptr = open(file_path, 'w')
답변
암호:
import os
script_path = os.path.abspath(__file__)
path_list = script_path.split(os.sep)
script_directory = path_list[0:len(path_list)-1]
rel_path = "main/2091/data.txt"
path = "/".join(script_directory) + "/" + rel_path
설명:
라이브러리 가져 오기 :
import os
__file__
현재 스크립트 경로를 얻는 데 사용하십시오 .
script_path = os.path.abspath(__file__)
스크립트 경로를 여러 항목으로 구분합니다.
path_list = script_path.split(os.sep)
목록에서 마지막 항목 (실제 스크립트 파일)을 제거하십시오.
script_directory = path_list[0:len(path_list)-1]
상대 파일의 경로를 추가하십시오.
rel_path = "main/2091/data.txt
목록 항목을 결합하고 상대 경로 파일을 추가하십시오.
path = "/".join(script_directory) + "/" + rel_path
이제 다음과 같이 파일로 원하는 것을 수행하도록 설정되었습니다.
file = open(path)
답변
파일이 상위 폴더에있는 경우 (예 : follower.txt, 간단히 사용할 수 있습니다open('../follower.txt', 'r').read()
