2015-01-09 3 views
6

파일을 만들 때이 오류가 발생합니다. 생성 된 .csv 파일을 가져 와서 일반 텍스트 파일에 저장하도록 설계되었습니다.IOError : [Errno 22] 잘못된 모드 ('w') 또는 파일 이름

날짜 및 시간 스탬프를 사용하여 실행 한 후에 새 파일을 작성하고 싶지만 파일을 생성 할 때 Errno 22가 표시되는 것 같습니다.

아이디어가 있으십니까?

import csv 
import time 

f = open(raw_input('Enter file name: '),"r") 

saveFile = open ('Bursarcodes_'+time.strftime("%x")+ '_'+time.strftime("%X")+ 
       '.txt', 'w+') 

csv_f = csv.reader(f) 

for row in csv_f: 
    saveFile.write('insert into bursarcode_lookup(bursarcode, note_id)' + 
        ' values (\'' + row[0] + '\', ' + row[1] + ')\n') 

f.close() 

saveFile.close() 
+3

'time.strftime ("% X")'는 '12 : 57 : 03 '과 같은 문자열을 반환합니다. OS에서 콜론이있는 파일 이름을 허용 했습니까? 마찬가지로, % x은''01/09/15 ''을 얻을 것입니다. "15_12 : 57 : 03.txt"파일을 포함하는 "Bursarcodes_01"과 "09"디렉토리가 이미 설정되어 있습니까? – Kevin

+0

이것은 정확히 문제였습니다. 수정 한 후에 그것은 매력처럼 작동합니다. – SergeProtector

답변

6

당신은 가질 수 없습니다 슬래시 (/) 및 콜론 (:하지만 유닉스에서 허용) 파일 이름에 있지만 strftime이 출력에서 ​​생성 정확히입니다.

파이썬은 당신을 도와 시도는 말한다 :

No such file or directory: 'Bursarcodes_01/09/15_19:59:24.txt' 

이 함께 time.strftime("%x") 교체 :

time.strftime("%X").replace(':', '_') 
+1

빠른 응답을 주셔서 와우 감사합니다. – SergeProtector

+1

@SergeProtector 도움이 되니 기쁩니다! –

1

cleaned-이와

time.strftime("%x").replace('/', '.') 

... 그리고 time.strftime("%X")을 확장 및 확장 버전 :

import csv 
import sys 
import time 

def make_output_fname(): 
    # Thanks to @Andrew: 
    return time.strftime("Bursarcodes_%x_%X.txt").replace("/", "-").replace(":", "-") 

def main(csv_fname=None, outfname=None, *args): 
    if not csv_fname: 
     # first arg not given - prompt for filename 
     csv_fname = raw_input("Enter .csv file name: ") 

    if not outfname: 
     # second arg not given - use serialized filename 
     outfname = make_output_fname() 

    with open(csv_fname) as inf, open(outfname, "w") as outf: 
     incsv = csv.reader(inf) 
     for row in incsv: 
      outf.write(
       "insert into bursarcode_lookup(bursarcode, note_id) values ('{0}', '{1}')\n" 
       .format(*row) 
      ) 

if __name__=="__main__": 
    # pass any command-line arguments to main() 
    main(*sys.argv[1:]) 

이제 명령 줄에서도 실행할 수 있습니다.

csv 파일의 모든 데이터 항목에 이스케이프 처리가되지 않은 작은 따옴표 (')가 있으면 잘못된 sql이 표시됩니다.

+0

와우 지금은 인상적입니다. 제 코드에서 알 수 없다면, 제가 파이썬에서 완전한 초보자라는 것을 확실히 알아 두십시오. 나는 너의 도움에 감사 드리며 놀 것이다. – SergeProtector