2016-10-01 2 views
1

파일 txt가 있습니다. 줄 바꿈이있는 곳에 ... 링크 중 일부는 링크입니다. 내 질문은 : 어떻게 내가이 모든 링크를 잡을 수 있고 다른 txt 파일에 저장할 수 있습니까? 나는 초보자입니다. txt 파일에서 링크 캐치

은 이걸로 시도했지만 작동하지 않습니다 :

filee = open("myfile.txt").readlines() 
out_file = open("out.txt","w") 
out_file.write("") 
out_file.close() 

for x in filee: 
    if x.startswith("http"): 
     out_file.write(x) 
     print (x) 
+2

무엇을에서 방법은 작동하지 않습니까? 쓰기 전의 파일을 닫고 있습니다. 쓰기 전입니다. 그게 문제가 될 것 같아. –

+2

사이드 노트 : 파일을 다룰 때는 ['with' statements] (https://www.python.org/dev/peps/pep-0343/)를 사용하십시오. 실수로 'close'호출을 생략 할 수 없으며 (close 호출이 필요하지 않음) 리소스를 사용할 수있는 시점을보다 쉽게 ​​알 수 있습니다. – ShadowRanger

답변

4

당신은 닫힌 파일에 쓸 수 없습니다. 여기

filee = open("myfile.txt").readlines() 
out_file = open("out.txt","w") 
out_file.write("") 

for x in filee: 
    if x.startswith("http"): 
     out_file.write(x) 
     print (x) 
out_file.close() 

깨끗한 버전 : : 그냥 코드의 끝 부분에 out_file.close()를 이동

# open the input file (with auto close) 
with open("myfile.txt") as input_file: 

    # open the output file (with auto close) 
    with open("out.txt", "w") as output_file: 

     # for each line of the file 
     for line in input_file: 

      # append the line to the output file if start with "http" 
      if line.startswith("http"): 
       output_file.write(line) 

는 또한 결합 할 수 있습니다를 두 가지로 :

# open the input/output files (with auto close) 
with open("myfile.txt") as input_file, open("out.txt", "w") as output_file: 

    # for each line of the file 
    for line in input_file: 

     # append the line to the output file if start with "http" 
     if line.startswith("http"): 
      output_file.write(line)