我是python的新手(制作了4个脚本来清理文件夹并移动一些内容),现在我面临新的挑战。
我有这个csv文件,其中包含有关某些pdf的数据(pdf名称,需要打印的次数等)
我有以下代码atm,并且一切正常,但是我发现它“不干净”,我希望有更好的格式化某些内容的方法。 这是我的代码:
import csv, shutil, os
with open('\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\OhGreen POS week 19.csv') as csvfile:
csvReader = csv.reader(csvfile, delimiter=';')
rows = csv.reader(csvfile)
headers = next(rows)
for row in csvReader:
NAAM = row[0]
Formaat = row[1]
Tekstkleur = row[2]
Gouvy = row[3]
LouvainLaNeuve = row[4]
Nannine = row[5]
Tournai = row[6]
SaintGeorges = row[7]
Aarschot = row[8]
Balen = row[9]
Ekeren = row[10]
Ninove = row[11]
SintKatelijneWaver = row[12]
Olen = row[13]
Zwijndrecht = row[14]
if Gouvy > "0":
file = NAAM + ".pdf"
path = ("\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\" + Formaat + "\\" + file)
dest = ("\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\2print\\" + Formaat + "\\" + NAAM + "_GOUVY" + ".pdf")
shutil.copy(path, dest)
print(dest , " changed name and moved to ", dest)
if LouvainLaNeuve > "0":
file = NAAM + ".pdf"
path = ("\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\" + Formaat + "\\" + file)
dest = ("\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\2print\\" + Formaat + "\\" + NAAM + "_LOUVAIN_LA_NEUVE" + ".pdf")
shutil.copy(path, dest)
print(dest , " changed name and moved to ", dest)
if Nannine > "0":
file = NAAM + ".pdf"
path = ("\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\" + Formaat + "\\" + file)
dest = ("\\\\fatboy.leleu.be\\Psm\\Mailing Templates\\OhGreen\\Verwerking\\2print\\" + Formaat + "\\" + NAAM + "_NANNINE" + ".pdf")
shutil.copy(path, dest)
print(dest , " changed name and moved to ", dest)
此代码针对csv中的每个城市名称(总共12个)继续进行 我想寻找一种使这种清洁剂更清洁的方法。 就像我不需要为每个城市创建一个if循环和所有标头名称等的循环一样。
欢迎任何提示。 PS:我不会使用Pandas,因为我无法正确安装它,并且在基本python中已经可以正常工作了
答案 0 :(得分:0)
首先,将字符串存储为变量。您似乎经常重复使用相同的字符串,因此,如果将其存储为变量BASE_PATH,则可以执行以下操作:
BASE_PATH = "\\\\fatboy.leleu.be\\Psm\\Mailing\\Templates\\OhGreen\\Verwerking\\"
path = BASE_PATH + Formaat + "\\" + file
甚至
BASE_PATH = "\\\\fatboy.leleu.be\\Psm\\Mailing\\Templates\\OhGreen\\Verwerking\\{}\\{}"
path = BASE_PATH.format(Formaat, file)
第二,您可以将要检查的变量存储为字典,并在其键上循环。例如:
BASE_PATH = "\\\\fatboy.leleu.be\\Psm\\Mailing\\Templates\\OhGreen\\Verwerking\\{}\\{}"
DEST_PATH = "\\\\fatboy.leleu.be\\Psm\\Mailing\\Templates\\OhGreen\\Verwerking\\2print\\{}\\{}.pdf"
name_index_mapping = {
"GOUVY": 3,
"LOUVAIN_LA_NEUVE": 4,
"NANNINE": 5
}
for (name, index) in name_index_mapping.items():
if row[index] > "0":
file = NAAM + ".pdf"
path = BASE_PATH.format(Formaat, file)
dest = DEST_PATH.format(Formaat, NAAM, name)
shutil.copy(path, dest)
print(path, "changed name and moved to", dest)
最后,您确定需要将值与文字字符串"0"
而不是数字0
进行比较吗?使用greater/smaller than
逻辑比较字符串会产生意外结果。