2016-07-13 2 views
0

그래서 *.styles*.layout 개의 파일을보고 해당 파일의 특정 문자열을 바꿀 Python 스크립트를 만들려고합니다. 나는 여러 가지 시도를했지만, 내가해야 할 일을 알아낼 수 없으며 심지어 다른 코드 샘플을 온라인으로 보더라도 이해하는 것이 훨씬 더 혼란 스럽다.파일의 문자열을 Python으로 바꿉니다

여기 내 코드는 현재 가지고 있습니다.

#!/usr/bin/python3 
# coding: utf-8 

import os 
import sys 
import fileinput 

f1 = open ('*.styles', 'r') # read *.styles 
f2 = open ('*.styles', 'w') # write *.styles 
f3 = open ('*.layout', 'r') # read *.layout 
f4 = open ('*.layout', 'w') # write *.layout 
for line in f1: 
    f2.write(line.replace('font-size=15','font-size=12')) # replace string for 
    f2.write(line.replace('font-size=14','font-size=12')) # files in *.styles 
    f2.write(line.replace('font-size=18','font-size=14')) 
    f2.write(line.replace('font-size=30','font-size=18')) 
    f2.write(line.replace('font-size=36','font-size=18')) 
    f2.write(line.replace('font-size=16','font-size=12')) 
    f2.write(line.replace('font-size=26','font-size=16')) 
    f2.write(line.replace('font-size=48','font-size=20')) 
    f2.write(line.replace('font-size=28','font-size=16')) 
    f2.write(line.replace('font-size=17','font-size=14')) 
    f2.write(line.replace('font-size=21','font-size=14')) 
f1.close() 
f2.close() 

for line in f3: 
    f4.write(line.replace('font-size=15','font-size=12')) # replace string for 
    f4.write(line.replace('font-size=14','font-size=12')) # files in *.layout 
    f4.write(line.replace('font-size=18','font-size=14')) 
    f4.write(line.replace('font-size=30','font-size=18')) 
    f4.write(line.replace('font-size=36','font-size=18')) 
    f4.write(line.replace('font-size=16','font-size=12')) 
    f4.write(line.replace('font-size=26','font-size=16')) 
    f4.write(line.replace('font-size=48','font-size=20')) 
    f4.write(line.replace('font-size=28','font-size=16')) 
    f4.write(line.replace('font-size=17','font-size=14')) 
    f4.write(line.replace('font-size=21','font-size=14')) 
f3.close() 
f4.close() 

print ("\n\n ## Done!\n\n") 
sys.exit(0) 

내가 포함 할 않은 "당신은 변경 사항을 적용 하시겠습니까? [Y/N]"간단한 예/아니오 사용자가 입력 한 대답과,하지만 그와 알아낼 조금 너무 복잡 있어요 While True:While False:

이 코드를 테스트하려는 파일에서 테스트를 실행하면이 오류를 테스트하는 데 오류가 발생합니다.

line 8, in <module> 
    f1 = open ('*.styles', 'r') # read *.styles 
FileNotFoundError: [Errno 2] No such file or directory: '*.styles' 

난 그렇게 명령 줄에서 실행할 수 있기를 원합니다.

$ string_search.py . 

은 그래서 당신은 그냥 현재 디렉토리와 폴더, 실제 디렉토리를 지정하지 않아도 해당 디렉토리 *.styles*.layout 파일이 들어있는 현재 디렉토리에있는 모든 파일을 변경합니다.

+0

[디렉터리에 필터링 된 파일 목록 가져 오기] (http : // stackoverflow.com/questions/2225564/get-a-filtered-of-a-directory-of-a-directory) –

+2

문자열 검색과 while 루프 및이 외의 모든 질문에 대한 정보를 왜 포함 시켰는지 모르겠다. 한 줄의 코드로 문제가 발생했습니다. 게시물 당 하나의 질문을 고수하고 * 최소 * 검증 가능한 예제를 사용하십시오. –

+0

@ Two-BitAlchemist - 요점을 놓치고 있는데, 이것이 하나의 질문입니다. 주요 질문은 파이썬이 지정된 모든 파일을 검색하고 특정 파일 내의 지정된 문자열을 바꿀 새 문자열로 바꾸는 방법입니다. 빠른 커밋 변경으로 많은 파일을 신속하게 처리 할 수 ​​있으므로 각 파일을 개별적으로 처리해야하는 시간을 절약 할 수 있습니다. –

답변

0

open은 하나의 파일을 엽니 다. 패턴과 일치하는 파일 모음을 여는 데 사용하려고하는 것 같습니다. 아마도 os.walk을보고 파일 디렉토리를 가로 지려하고 각각을 개별적으로 처리 할 수 ​​있습니다.

1

Scott Hunter가 쓴대로 open은 하나의 파일을 엽니 다. 일치하는 파일의 목록을 가져와 루프마다 각각 open을 호출해야합니다. 방법은 다음과 같습니다.

하나의 파일로 처리하는 기능을 만듭니다

import os 
for dirpath, dirnames, filenames in os.walk('.'): 
    for filename in filenames: 
    # Instead of .endswith, you can use the fnmatch module to match on '*.styles'. 
    if filename.endswith('.styles'): 
     process_file(os.path.join(dirpath, filename)) 
: 디렉토리와 파일의 재귀 열거를 들어,

import glob 
for filename in glob.glob('*.styles'): 
    process_file(filename) 

또는이 같은 :

def process_file(filename): 
    print(filename) 
    # ... open(filename) ... 
    # ... open(filename, 'w') ... 

는 다음과 같이 함수를 호출을

-1

죄송합니다. 아직 말씀 드릴 수는 없지만 그렇게해야합니다. 먼저 내가 파일을 반복하고 수정할 것 :

for current_path, dirs, files in os.walk(Your_Path_With_Files)): 
      for file in files: 
       if file.endswith('.styles'): 
        #here you store the file path somewhere 
        #I'm not 100% the exact way to have the full path, 
        # but it's with os.path.join() to have a clean path 
        #list_path_styles_files 

을 다음 수정해야하는 파일에서 모든 경로가있을 때 : 내가 좋아하는 fileinput.input 뭔가 관리

for the_path in list_path_styles_files: 
     for line in fileinput.input(the_path, inplace=1): 
       line = line.replace('font-size=15','font-size=12') 
       line = ... 
       ... 
       print line 

이렇게하면 줄을 하나씩 읽은 다음 원하는대로 줄을 수정 한 다음 파일에 넣습니다.

관련 문제