python - for循环函数调用文件解析

标签 python python-2.7

我认识到这段代码效率极低。

我在这里完全不知所措,我计划删除该函数并仅使 main 中的代码程序化。但我希望有人能解释我在这里看到的内容。 main() 中的循环运行并调用 matchName()。 matchName() 执行它的循环,当它应该返回下一个“vtRow”时,它只是停止执行。因此输出是 vtData 的第一条记录和 adData 的每条记录。

import csv, re

def main():
    #1st word
    oneWord = re.compile( '\A([\w]+)' )
    #1st 3
    first3 = re.compile( '\A([\w]{3})' )
    #last 3
    last3 = re.compile( '(?=([\w]{3})$)' )

    mArray = [ oneWord, first3, last3 ]
    adFile =  open('adData.csv', 'rb')
    adFields = ('lName','fName','cNum','addy','city','state','zip','phone','sex')
    adData = csv.reader(adFile, dialect='excel')

    vtFile =  open('data360.csv','rb')
    vtFields = ('ref','fName','lName')
    vtData = csv.reader(vtFile, dialect='excel')

    for vtRow in vtData:
        matchName(vtRow, adData, mArray) # appears that this runs once and exits

def matchName(curVtRow, adData, mArr):
    lName = curVtRow[4].lower()
    fName = curVtRow[3].lower()
    Posib = []

    for row in adData:
        cName = row[0].lower() 
        print "vt " + lName + " ; ad " + cName
    return 1

if __name__ == "__main__":
    main()

最佳答案

问题在于,使用 adData 进行循环会导致读取 adFile,因此在第一次调用 matchName() 后,该文件将已被一路读取,因此 adData 不会被循环,因为 adData.next() 不会产生任何结果(因此 print 语句将不会被执行)。我建议在调用 matchName() 之后放置 adFile.seek(0)。请注意,仅重新创建 adData 是行不通的;我最近发现 csv 读取器会更新其底层对象的文件位置,而不是自行跟踪它。

关于python - for循环函数调用文件解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368509/

相关文章:

python-2.7 - 运行 pytest 断言整个脚本的输出

python - 在 django 生产中记录所有 sql 查询是个好主意吗?

python - Django REST API 模板DoesNotExist Apache

python - ensure_future 在异步模块中不可用

Cygwin64 上的 Python 2.7.5 : requests installation fails

python - docker -py : Connection reset by peer

Python,将输出编码为 UTF-8

python - 将 Pandas 数据框转换为以第一列为键的字典

python - 如何在 Python 数据框中同时替换多行?

python - PySpark:类型错误:StructType 无法接受类型 <type 'unicode' > 或 <type 'str' > 的对象