2017-11-27 3 views
0

오후,Python 2.7 - CSV를 반복합니다.

다음 Python 2.7 코드가 있습니다. 다음을 수행하고 싶습니다.

  1. 'ofile'변수 값이 들어있는 CSV 파일을 읽으십시오.
  2. 아래 스크립트를 실행하고 CSV의 각 행에 대해 반복하십시오.
  3. CSV 파일에는 헤더를 포함하지 값 'ofile'는이있다 - 행에 하나씩 열 A에

나 대신 수동으로 ofile 변수를 업데이트 한 후이 스크립트를 실행하고, 내가 자동화 싶습니다 이 과정.

미리 감사드립니다.

import time 
import pysftp 
import sys 
import os 
from datetime import datetime 
import calendar 
import zipfile 
import re 

ofile = 'abc_' 
oupload = pysftp.Connection(host="xxxx", username="sxx", password="xNxxxx") 

d = datetime.utcnow() 
unixtime=calendar.timegm(d.utctimetuple()) 

import datetime 
month = datetime.datetime.now().strftime("%m") 

string = ofile+month+".*\.txt$" 

possibleFiles = oupload.listdir("/") 
for filename in possibleFiles: 
     filedate = re.search(string, filename) 
     if filedate: 
      newfile = filename 


timestamp = oupload.stat(newfile).st_atime 

if timestamp != unixtime: 

     newtime=unixtime + 1800 
     zipname = ofile+str(newtime)+'.sync.zip' 

     create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED) 

     oupload.get(newfile, newfile) 
     oupload.close() 

     newfilename = ofile+str(newtime)+'.sync' 
     os.rename(newfile, newfilename) 


     create_zip.write(newfilename) 

     create_zip.close() 


else: 

     print "No file found" 

CSV 파일에는 헤더가없는, 오직 여기에 열 A의 파일 이름을 가지고하는 것은 조각입니다 : 먼저 함수에 스크립트를 변환 할 필요가

filenamec 
filename_b 
filename_erf 
+1

csv 파일의 예와 예상 출력/그 예제 파일에 대한 결과. 그것을 작게 유지하십시오. 몇 줄. – timgeb

+0

하나의 열만 있습니까? 구분 기호는 쉼표'또는'\ t' 탭입니까? 이 정보는 파일을 올바르게 구문 분석하는 데 필요합니다. –

+0

쉼표로 구분됨 - 감사합니다. 단 하나의 열. 열 A –

답변

0

, 당신은 각 반복 줄을 csv 파일의 경우 필요한 값을 추출하고이를 ofile 변수에 할당합니다. 마지막으로 인수로 ofile을 전달하는 함수를 실행합니다. 실제 CSV 예제를 게시하지 않았으므로 정확하지 않을 수 있습니다. 구현은 다음과 유사해야합니다.

import time 
import pysftp 
import sys 
import os 
from datetime import datetime 
import calendar 
import zipfile 
import re 


def myscript(ofile): 
    oupload = pysftp.Connection(host="xxxx", username="sxx", password="xNxxxx") 
    d = datetime.utcnow() 
    unixtime=calendar.timegm(d.utctimetuple()) 
    month = datetime.now().strftime("%m") 
    string = ofile+month+".*\.txt$" 

    possibleFiles = oupload.listdir("/") 
    for filename in possibleFiles: 
      filedate = re.search(string, filename) 
      if filedate: 
       newfile = filename 

    timestamp = oupload.stat(newfile).st_atime 
    if timestamp != unixtime: 
     newtime=unixtime + 1800 
     zipname = ofile+str(newtime)+'.sync.zip' 
     create_zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED) 
     oupload.get(newfile, newfile) 
     oupload.close() 
     newfilename = ofile+str(newtime)+'.sync' 
     os.rename(newfile, newfilename) 
     create_zip.write(newfilename) 
     create_zip.close() 

    else: 
     print "No file found" 


mycsv = 'mydocument.csv' 

with open(mycsv, 'r') as f: 
    for line in f: 
     if not line.startswith('\n'): #skip empty lines 
      ofile = line.strip() #assuming you have only one column 
      myscript(ofile) 
+0

감사합니다. CSV는 다음과 같습니다. column a - row1 : abcefg_ columb a - row 2 : abcjjj –

+0

여기서 ofile = # 여기서 변수를 추출하십시오. 어떻게 변수를 추출합니까? 감사합니다 –

+0

나는 또한이 오류가 발생합니다 : "d = datetime.utcnow() UnboundLocalError : 할당하기 전에 로컬 변수 'datetime'이 참조되었습니다. 미리 감사드립니다. –