【问题标题】:Python 2.7 - iterate through a CSVPython 2.7 - 遍历 CSV
【发布时间】:2017-11-27 16:51:02
【问题描述】:

下午,

我在下面有以下 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 列中的文件名。这是一个 sn-p:

filenamec
filename_b
filename_erf

【问题讨论】:

  • 我们需要查看您的 csv 文件的示例以及该示例文件的预期输出/结果。保持小。几行。
  • 它只有一列吗?分隔符是逗号, 还是制表符\t?此信息是正确解析文件所必需的。
  • 逗号分隔 - 谢谢,只有一栏。 A栏
  • 你不能用记事本打开那个文件并张贴前几行吗?我需要知道是否有标题、任何评论等。
  • 你好,和上面一模一样,没有标题,上面只是复制粘贴。感谢您对此的帮助。

标签: python python-2.7 csv


【解决方案1】:

您需要先将脚本转换为函数,然后遍历 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)

【讨论】:

  • 谢谢,CSV 如下所示:a 列 - 第 1 行:abcefg_ 第 2 行:abcjjj
  • 你在哪里有ofile = #extract your variable here - 我如何在那里提取变量?谢谢
  • 我也收到此错误:“d = datetime.utcnow() UnboundLocalError: local variable 'datetime' referenced before assignment”提前致谢
  • 请至少发布一行您的 csv。否则我无法建议任何解析
  • filename_a 这是单元格 A1 中的内容 - 不幸的是,我无法将文件附加到 cmets 中。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 2020-06-25
  • 2020-01-26
  • 1970-01-01
  • 2019-09-24
  • 2019-11-11
  • 1970-01-01
相关资源
最近更新 更多