【发布时间】:2014-10-21 13:03:15
【问题描述】:
我正在编写一个脚本,该脚本需要将唯一 ID 附加到文件名。
文件名取自文本文件(第一个函数),传递给格式化它的第二个函数,然后传递给第三个函数,该函数应该搜索具有多列的 .csv 文件,找到正确的行(包含通过其他两个函数传入的值的行)并从“FID”列中的那一行获取值(作为 int 或字符串)。然后它应该打印这个值。
代码:
def get_file_name():
# this func gets the name of the file to be renamed
before_rename = open('C:/Users/my.path/before_rename.txt', 'r')
to_be_renamed_unf = before_rename.readline()[1:]
# remove the end CRs & LFs off of the string
to_be_renamed = to_be_renamed_unf.strip()
print("File name: " + to_be_renamed)
return to_be_renamed
def get_fname():
# get farmer name
file_name = get_file_name()
farmer_name = re.sub('[^A-Z]', ' ', file_name).rstrip().lstrip()
print(farmer_name)
return farmer_name
def get_id_from_file():
# search csv for COOP & Name to find the FID
csvfile = 'C:/Users/my.path/csv_file_to_read_from.csv'
# create a dictionary from the csv
csv_dict = csv.DictReader(open(csvfile))
fname = get_fname()
coop_name = 'CALMAN'
for row in csvfile:
if fname and coop_name in row:
farmer_id = int(row['FID'])
print(farmer_id)
get_id_from_file()
以及当前的输出:
File name: unformatted_file_NAME 03928
NAME
所以看起来它完全跳过了搜索循环;因为这是前两个函数的预期输出,我没有收到任何错误。
一些 .csv:
FID,Name,COOP
12345-29981662553784,bar FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
12345-29981662553784,FOO BAR, FOOBAR
【问题讨论】:
-
到目前为止我发现了两个问题。首先,
for row in csvfile将遍历文件名的每个字母。为避免混淆,该变量的更好名称可能是csv_file_name。二、fname and coop_name in row不等同于(fname in row) and (coop_name in row),它等同于bool(fname) and (coop_name in row)。 -
有没有办法让它们都成为布尔值?然后我如何遍历整个 csv 行?
-
我不完全明白你想要做什么,但你可能想遍历
csv_dict,而不是csvfile。