【发布时间】:2020-01-31 19:49:11
【问题描述】:
我有一段代码接受带有文件名列表的 .csv 作为输入,然后将文件名分解为其组成部分,并将它们与一些其他字符一起重新排序。
输入示例:
3006419_3006420_ENG_FRONT.jpg
输出示例:
;E3006419_3006420_FRONT_Image_Container;
但是,我想将 for 循环中将文件名拆分为一个函数,以便我可以在其他地方调用,这样我就可以在第二个 for 循环中重新使用它,该循环以不同的格式输出.但是,当我尝试定义一个函数时,我的变量似乎存在范围错误,无法在 output.write 语句中使用它们。
工作代码
from csv import reader
import sys
if len(sys.argv) != 2:
print('USAGE ERROR:\nRun like "python <script.py> <input file.csv>"') #error message if code is not run with correct number of arguments
exit()
file = open(sys.argv[1]) #open input file
output = open('output.impex','w+') #define output impex file
for line in file:
nameAndExtension = line.split('.') #split file into filename and file extension
name = nameAndExtension[0]
extension = nameAndExtension[1].replace('\n','') #save file extension as variable extension and remove \n
elements = name.split('_') #split filename into constituent elements. Filenames are formatted as PARENTSKU_CHILDSKU_LANG_ANGLE.extension, eg '3006419_3006420_ENG_FRONT.jpg'
parentSKU = elements[0]
childSKU = elements[1]
lang = elements[2]
angle = elements[3]
output.write(";E" + parentSKU + "_" + childSKU + "_" + angle + '_Image_Container;\n')
非工作代码:
from csv import reader
import sys
if len(sys.argv) != 2:
print('USAGE ERROR:\nRun like "python <script.py> <input file.csv>"') #error message if code is not run with correct number of arguments
exit()
file = open(sys.argv[1]) #open input file
output = open('output.impex','w+') #define output impex file
def lineSplitting(x):
nameAndExtension = x.split('.') #split file into filename and file extension
name = nameAndExtension[0]
extension = nameAndExtension[1].replace('\n','') #save file extension as variable extension and remove \n
elements = name.split('_') #split filename into constituent elements. Filenames are formatted as PARENTSKU_CHILDSKU_LANG_ANGLE.extension, eg '3006419_3006420_ENG_FRONT.jpg'
parentSKU = elements[0]
childSKU = elements[1]
lang = elements[2]
angle = elements[3]
for line in file:
lineSplitting(line)
output.write(";E" + parentSKU + "_" + childSKU + "_" + angle + '_Image_Container;\n')
我收到“NameError: name 'parentSKU' is not defined”我认为因为变量范围的原因 - 但我不知道我需要做什么才能使变量可重用在for循环中。我需要做什么才能将所有拆分和变量定义变成一个函数?
【问题讨论】:
-
你没有从函数返回任何东西
标签: python function for-loop variables scope