如何读取CSV,创建QR码,并将其文件名写入新列?

时间:2017-10-03 19:51:04

标签: python csv qr-code

我正在编写一个Python脚本,用于从csv中的第一列生成QR代码(与本地名称连接),该部分运行良好。 csv只有三列,如下所示:

ID    First    Last
144   Jerry    Seinfeld
491   George   Costanza
104   Elaine   Benes
99    Cosmo    Kramer

我使用我的Python脚本获取该文件,在ID s(在本例中为“NBC”)附加前缀,然后为新文件夹中的每条记录创建QR码。它有点长,但所有这些似乎也可以正常工作:

import csv
import qrcode
import os
import shutil
import time
import inquirer

#Identify Timestamp
timestr = time.strftime("%Y%m%d-%H%M%S")

local = 'NBC'

#Load csv
filename = "stackoverflowtest.csv"

#Path to new local folder
localfolder = local
localimagefolder = localfolder+'/image'
localfilefolder = localfolder+'/files'

#Check/create folders based on local
if not os.path.exists(localfolder):
    os.makedirs(localfolder)
if not os.path.exists(localimagefolder):
    os.makedirs(localimagefolder)
if not os.path.exists(localfilefolder):
    os.makedirs(localfilefolder)

#Copy uploaded file to their local's file folder
shutil.copy2(filename, localfilefolder+'/'+local+'-'+timestr+'.csv') # complete target filename given

#Read csv and generate QR code for local+first column of csv
with open(filename, 'rU') as csvfile:
    next(csvfile, None) #skip header row
    reader = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)

    for i, row in enumerate(reader):
        labeldata = row[0] #Choose first column of data to create QR codes
        print labeldata

        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )

        qr.add_data(local+"-"+labeldata)
        qr.make()

        img = qr.make_image()
        img.save(localimagefolder+"/"+local+"-"+labeldata+".png".format(i)) #Save image

创建NBC文件夹,将每个csv文件复制到一个子文件夹中,并为每个ID创建QR码(NBC-144NBC-491NBC-104NBC-99)在另一个。

我遇到问题的部分是打开csv并将文件路径/文件名写回csv(或者从我读过的csv的副本,我可能不能这样做同一个)。这可能吗?

我最接近一个有效的脚本是附加带有ID的本地名称并将其写回一列,但我似乎无法弄清楚如何对变量做同样的事情,更不用说了文件路径/文件名:

import csv
import os
import sys

filename = 'stackoverflowtest.csv'
newfilename = 'stackoverflowtest2.csv'
local = 'NBC'

with open(filename, 'rU') as f:
    reader = csv.reader(f)
    with open(newfilename, 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = row[0:] + ['-'.join([local, row[0]])]
            writer.writerow(new_row)

是否可以在现有脚本中编写类似的内容来为文件路径和文件名添加列?我尝试的所有东西都会中断 - 特别是如果我尝试在同一个脚本中执行此操作。

编辑:

这是我最接近覆盖现有文件的尝试

f=open(newfilename,'r+')
w=csv.writer(f)
for path, dirs, files in os.walk(path):
    for filename in files:
        w.writerow([newfilename])

它还在一个单独的脚本中。

1 个答案:

答案 0 :(得分:1)

由于我无法直接在您的问题中运行代码,因此我不得不在下面的内容中对其中的部分内容进行注释以进行测试,但认为它可以在一个脚本的一个循环中完成您想要的所有内容。

import csv
#import qrcode
import os
import shutil
import time
#import inquirer

# Identify Timestamp
timestr = time.strftime("%Y%m%d-%H%M%S")

local = 'NBC'

# Load csv
filename = "stackoverflowtest.csv"

# Path to new local folder
localfolder = local
localimagefolder = os.path.join(localfolder, 'image')
localfilefolder = os.path.join(localfolder, 'files')

# Check/create folders based on local
if not os.path.exists(localfolder):
    os.makedirs(localfolder)
if not os.path.exists(localimagefolder):
    os.makedirs(localimagefolder)
if not os.path.exists(localfilefolder):
    os.makedirs(localfilefolder)

# Copy uploaded file to their local's file folder
target = os.path.join(localfilefolder, local+'-'+timestr+'.csv') # Target filename
#shutil.copy2(filename, target)  # Don't need to do this.

# Read csv and generate QR code for local+first column of csv
with open(filename, 'rb') as csvfile, open(target, 'wb') as outfile:
    reader = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
    writer = csv.writer(outfile, delimiter=',', dialect=csv.excel_tab)
    next(reader)  # Skip header row.

    for row in reader:
        id, first, last = row

#        qr = qrcode.QRCode(
#            version=1,
#            error_correction=qrcode.constants.ERROR_CORRECT_L,
#            box_size=10,
#            border=4,
#        )
#
#        qr.add_data(local+"-"+id)
#        qr.make()
#
#        img = qr.make_image()
        imagepath = os.path.join(localimagefolder, local+"-"+id+".png")
#        img.save(imagepath) # Save image.
        print "saving img:", imagepath

        writer.writerow(row + [local+'-'+id, imagepath])

样本输入数据的输出:

144,Jerry,Seinfeld,NBC-144,NBC/image/NBC-144.png
491,George,Costanza,NBC-491,NBC/image/NBC-491.png
104,Elaine,Benes,NBC-104,NBC/image/NBC-104.png
99,Cosmo,Kramer,NBC-99,NBC/image/NBC-99.png