Python 에서 파일 과 디 렉 터 리 를 조작 하 는 방법(file 대상/os/os.path/shutil 모듈)
다음은 두 단락 의 코드 를 통 해 이 를 학습 한다.
1.학습 파일 대상
2.os/os.path/shutil 모듈 학습
1.file 대상 학습:
프로젝트 에 서 는 파일 에서 설정 파 라 메 터 를 읽 어야 합 니 다.python 은 JSon,xml 등 파일 에서 데 이 터 를 읽 은 다음 Python 의 내용 데이터 구조 로 변환 할 수 있 습 니 다.
다음은 JSon 파일 을 예 로 들 어 JSon 파일 에서 설정 파 라 메 터 를 가 져 옵 니 다.
코드 실행 환경:python 27+eclipse+pydev
JSon 파일 이름:configfile.json
JSON 파일 경로:C:\\temp\\configfile.json
JSon 파일 의 내용:
{"user":"Tom","username":"root_tom","password":"Jerryispig","ipaddr":"10.168.79.172"}
{"user":"Jerry","username":"root_jerry","password":"Tomispig","ipaddr":"10.168.79.173"}
코드 는 다음 과 같 습 니 다:
import json #use json file ,you must import json.  
  
def verify_file_class():  
  file_json=open(r'C:\temp\config_file.json','r') # open config_file.json file with 'r'  
  for each_line in file_json.readlines():     #read each line data  
    print each_line               # verify each line data by print each line data  
    
    each_line_dict = json.loads(each_line)    # each row of the data into the 'dict'type of python  
      
    print 'the type of the each_line_dict:{type}'.format(type=type(each_line_dict)) # verify whether is‘dict'type  
      
    print 'user is: {user}'.format(user=each_line_dict['user'])  
    print 'username is: {username}'.format(username=each_line_dict['username'])  
    print 'password is: {password}'.format(password=each_line_dict['password'])  
    print 'ipaddr is: {ipaddr} 
'.format(ipaddr=each_line_dict['ipaddr'])  
      
    #use username,password, ipaddr ( enjoy your programming ! )  
    
  file_json.close()  # don't forgot to close your open file before.  
  
if __name__ == '__main__':  
  verify_file_class() 
{"user":"Tom","username":"root_tom","password":"Jerryispig","ipaddr":"10.168.79.172"}  
the type of the each_line_dict:<type 'dict'>  
user is: Tom  
username is: root_tom  
password is: Jerryispig  
ipaddr is: 10.168.79.172   
  
{"user":"Jerry","username":"root_jerry","password":"Tomispig","ipaddr":"10.168.79.173"}  
the type of the each_line_dict:<type 'dict'>  
user is: Jerry  
username is: root_jerry  
password is: Tomispig  
ipaddr is: 10.168.79.173 조금 큰 항목 에서 빠 질 수 없 는 것 은 디 렉 터 리 를 여러 가지 조작 해 야 합 니 다.
예 를 들 어 디 렉 터 리 생 성,디 렉 터 리 삭제,디 렉 터 리 통합 등 각종 디 렉 터 리 작업.
다음은 code 를 예 로 들 어 os/os.path/shutil 모듈 에 대한 학습 을 실현 합 니 다.
아래 코드 는 폴 더 설치 에 있 는 모든 파일(파일 과 폴 더 가 들 어 있 음)을 삭제 합 니 다.
메모:폴 더 installation 에 있 는 모든 파일 을 삭제 하고 installation 이 폴 더 를 삭제 하지 않 습 니 다.
코드 는 다음 과 같 습 니 다:
코드 실행 환경:python 27+eclipse+pydev
import os 
import shutil  
 
 
def empty_folder(dir): 
  try: 
    for each in os.listdir(dir): 
      path = os.path.join(dir,each) 
      if os.path.isfile(path): 
        os.remove(path) 
      elif os.path.isdir(path): 
        shutil.rmtree(path) 
    return 0 
  except Exception as e: 
    return 1 
 
 
if __name__ == '__main__': 
  dir_path=r'D:\installation' 
  empty_folder(dir_path) 
1. os.listdir(dir) 
2. os.path.join(dir, each) 
3. os.path.isfile(path) /os.path.isdir(path) 
4. os.remove(path) 
5. shutil.rmtree(path) 
1. os.listdir(dir)
이 함 수 는 지정 한 디 렉 터 리 의 모든 파일 과 디 렉 터 리 이름 으로 구 성 된 목록 을 되 돌려 줍 니 다.
목록 을 되 돌려 주 는 것 입 니 다.이 목록 의 요 소 는 지정 한 디 렉 터 리 에 있 는 모든 파일 과 디 렉 터 리 로 구성 되 어 있 습 니 다.
>>> import os 
>>> os.listdir(r'c:\\') 
['$Recycle.Bin', 'Documents and Settings', 'eclipse', 'hiberfil.sys', 'inetpub', 'Intel', 'logon_log.txt', 'MSOCache', 'pagefile.sys', 'PerfLogs'<span style="font-family: Arial, Helvetica, sans-serif;">]</span> 디 렉 터 리 와 파일 이름 또는 디 렉 터 리 연결
>>> import os 
>>> os.path.join(r'c:\doog',r's.txt') 
'c:\\doog\\s.txt' 
>>> os.path.join(r'c:\doog',r'file') 
'c:\\doog\\file' os.path.isfile(path)은 path 가 파일 인지 아 닌 지 를 판단 하 는 데 사 용 됩 니 다.파일 이 라면 True 로 돌아 갑 니 다.그렇지 않 으 면 False 로 돌아 갑 니 다.
os.path.isdir(path)는 path 가 디 렉 터 리 인지 아 닌 지 를 판단 하 는 데 사 용 됩 니 다.디 렉 터 리 라면 True 로 돌아 갑 니 다.그렇지 않 으 면 False 로 돌아 갑 니 다.
>>> import os 
>>> filepath=r'C:\Program Files (x86)\Google\Chrome\Application\VisualElementsManifest.xml' 
>>> os.path.isdir(filepath) 
False 
>>> os.path.isfile(filepath) 
True 지정 한 파일 을 삭제 합 니 다.파일 이 비어 있 든 없 든 삭제 할 수 있 습 니 다.
메모:이 함 수 는 파일 만 삭제 할 수 있 고 디 렉 터 리 를 삭제 할 수 없습니다.그렇지 않 으 면 오류 가 발생 할 수 있 습 니 다.
>>> import os 
>>> os.removedirs(r'c:\temp\david\book\python.txt') 만약 디 렉 터 리 에 파일 과 디 렉 터 리 가 있다 면,즉 하나의 디 렉 터 리 에 몇 개의 하위 디 렉 터 리 가 있 든,이 하위 디 렉 터 리 에는 몇 개의 디 렉 터 리 와 파일 이 있 든 상관없다.
이 상위 디 렉 터 리 를 삭제 하고 싶 습 니 다.(주의:이 디 렉 터 리 와 이 디 렉 터 리 의 모든 파일 과 디 렉 터 리 를 삭제 하 는 것 입 니 다.)
어떻게 할 까요?
shutil 모듈 의 rmtree()함 수 를 사용 해 야 합 니 다.
>>> import shutil 
>>> shutil.rmtree(r'C:
o1') 이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.