【发布时间】:2021-10-24 09:48:37
【问题描述】:
我有以下场景:
我正在尝试查看文件名列表中是否存在特定文件名。但是,如果该文件不存在,我想用其他字符串修改我的字符串的不匹配元素,直到所需的文件名与列表中的任何文件名匹配。为了做到这一点,我决定将我想要的文件名拆分为不同的组件并将它们添加到字符串中;所以,我会更容易识别不匹配的组件。 我的代码如下:
# Define the components of the file name to be match
filename_components = ['p', '2500', '_g', '-1.0', '_m', '0.0', '_t', '00', '_', 'st', '_z', '-5.00', '_a', '+0.40', '_c+0.00_n+0.00_o', '+0.40', '_r+0.00_s+0.00.mod']
# Import the text file containing the list of file names
file_names = open('files_list.txt', 'r').read()
file_name = filename_components[0]
# Iterate over all the file components to match them with the file list
for n in range(len(filename_components)):
# If the file name exists, add the next component
if file_name in file_names:
print(f'File name: {file_name} is matching! Adding {filename_components[n+1])
file_name += filename_components[n+1]
# While the file name does not match, perform a swap of the component until the file name matches
while file_name not in file_names:
print(f'{file_name} not matched')
'''
some code that swaps the components
.
.
.
'''
file_name += filename_components[n+1]
# If the file name matches with the swapped component, break the while loop
if file_name in file_names: break
如果我运行这段代码,我会得到这个输出:
File name: p is matching! Adding 2500
File name: p2500 is matching! Adding _g
File name: p2500_g is matching! Adding -1.0
p2500_g-1.0 not matched
p2500_g+0.0 not matched
p2500_g+1.0 not matched
p2500_g+2.0 not matched
File name: p2500_g+3.0 is matching! Adding _m
File name: p2500_g+3.0_m is matching! Adding 0.0
File name: p2500_g+3.0_m0.0 is matching! Adding _t
File name: p2500_g+3.0_m0.0_t is matching! Adding 00
File name: p2500_g+3.0_m0.0_t00 is matching! Adding _
File name: p2500_g+3.0_m0.0_t00_ is matching! Adding st
File name: p2500_g+3.0_m0.0_t00_st is matching! Adding _z
File name: p2500_g+3.0_m0.0_t00_st_z is matching! Adding -5.00
此时,我知道将这个 -5.00 组件添加到字符串中不会匹配,因为我自己测试了它。因此,我希望调用我的 while 循环。但是,不满足匹配条件,也不满足不匹配条件。我在 while 循环之外和主 For 循环中放置了一个打印语句,以确保 for 循环仍在工作,并且它确实如此,它迭代了列表的其余组件。但是,没有更多的组件被添加到字符串中,也没有满足 if 或 while 循环条件。如果一切正常,我最终的预期结果应该是:
File name: ....mod is matching!
我知道我最终会遇到 IndexError,但我知道如何解决它。我只是需要帮助来理解,为什么我的 while 循环在其余的迭代中不起作用?
【问题讨论】:
-
file_names = open('files_list.txt', 'r').read():这会将整个文件读取为单个字符串,包括换行符。假设文件中的文件名由换行符分隔,那是您想要读取files_list.txt文件的方式吗? -
您可能希望 (a) 分隔行,(b) 去除换行符(可能还有任何前导/尾随空格),以及 (c) 完成后关闭文件。
-
程序的其余部分也有类似的问题;您需要仔细检查并检查每一行在做什么,可能结合使用
print语句和How to debug small programs 指南中的一些技术
标签: python for-loop while-loop string-matching