2012-03-07 3 views
0

새 파일을 수정하고 화면에 출력 할 때까지 계속 실행되는 동안 코드가 마지막으로 수정 된 파일을 받아서 인쇄해야합니다. 그러나 typeError를 가져 오는 kepp이 있습니다. TypeError : 유니 코드로 강제 변환 : string 또는 버퍼가 필요합니다. int가 있습니다.디렉토리의 쓰루 파일을 반복합니다.

import os, sys, re, time 
from datetime import date, timedelta, datetime 
from time import localtime 

files = os.listdir('dir_path') 

files = [f for f in files if re.search('.csv', f, re.I)] 
files.sort 

d = datetime.now() - timedelta(days = 30) 
d = d.timetuple() 

oldfiles = 0 
newfiles = 0 
for file in files: 
    filetimesecs = os.path.getmtime('dir_path' + file) 
    filetime = localtime(filetimesecs) 

if filetime < d: 
    oldfiles += 1 
if filetime > d: 
    newfiles += open(files, 'r') 
    for k in newfiles: 
     sys.stderr.write(k) 
    while True: 
     time.sleep(2) 
     print"new: %s" % newfiles 
+3

들여 쓰기가 잘못되었을 수 있습니다. 그것을 제발 바꿔 주시겠습니까? –

+0

아니요 newfiles를 + = open (files, 'r') sys.stderr.write (k)에 넣고 newfiles를 +1하십시오 : newfiles를 입력하십시오. – mintgreen

+3

@SvenMarnach 'if' 블록들의 들여 쓰기를 언급하고 있습니다. 마치'for' 루프에있는 것처럼 보입니다. 또한, 당신이 가지고있는 논리는 당신의 설명이 말하는 것을 확실히하지 않을 것입니다. 모든 파일을 한 번 반복 한 다음 중지합니다. 그리고 우리를 더 쉽게 만들기 위해, 오류는 무엇에 던져지고 있습니까? 마지막으로,'dir_path'가 문자열 리터럴이 아니라 매개 변수라는 것을 의미한다고 생각합니다. –

답변

1

이상하게 보이는 코드에는 여러 가지가 있습니다. 예 :

files = [f for f in files if re.search('.csv', f, re.I)] 

이게 진짜 원하는가요? 점은 개행을 제외한 모든 문자와 일치합니다. 원하는 동작을 얻으려면이 코드를 이스케이프 처리해야하거나 f.endswith('.csv')으로 테스트하면됩니다.

files.sort 

이것은 함수 호출이 아닙니다. 디렉토리 경로 및 파일 이름을 가입 os.path.join()를 사용하는 것이 좋습니다 files.sort()

filetimesecs = os.path.getmtime('dir_path' + file) 

해야한다.

files 변수는 문자열이 아니라 목록입니다. 맞습니까? 이 줄에 오류가 없니?

+0

그래 내가 어디서 얻을 수 있니? – mintgreen

+0

@mintgreen : 좋아, '파일'에서 '파일'로 변경하고 무슨 일이 일어나는지 확인해. –

+0

IOError : [Errno 2] 해당 파일이나 디렉토리가 없습니다. '21B8A1E8c.csv' – mintgreen

1

우리는 몇 가지 유형 오류가있는 것처럼 보입니다. 가능한 한 최선을 다하려고합니다.

oldfiles = 0 
# if newfiles is an integer, I'm not sure that it will be 
# as helpful to you, I think you'd really rather have a list 
newfiles = list() 
for file in files: 
    filetimesecs = os.path.getmtime('C:/tmp/' + file) 
    filetime = localtime(filetimesecs) 
    if filetime < d: 
     oldfiles += 1 
    if filetime > d: 
     newfiles.append(open('C:/tmp/' + file, 'r')) 
     for k in newfiles: 
      # read the entire file and write it to standard error 
      sys.stderr.write(k.read()) 

# I believe you want the while out here, after everything is complete 
# it would seem that you would want the newfiles loop within the first 
# for loop 
while True: 
    time.sleep(2) 
    print "new: %s" % newfiles 

희망이 있습니다.

+0

ok 감사하지만 파일의 내용을 인쇄 할 때 파일이 메모리에있는 파일 이름과 위치를 인쇄하는 데 문제가 있습니까 ??? – mintgreen

+0

@mintgreen 이제'sys.stderr.write (k.read())'는 전체 파일을 읽고 표준 오류에 씁니다. – macduff

+2

파일의 문자열 표현이 아닌 내용을 인쇄하려면 내용을 가져와야합니다. @macduff가 암시 하듯이, 그것은'k' 대신'k.read()'를 사용하는 것을 의미합니다. 즉, 잠재적으로 커질 수있는 전체 파일을 표준 오류에 버리지 않도록주의해야합니다. –

관련 문제