提问人:Djaq Harris 提问时间:8/4/2023 更新时间:8/4/2023 访问量:26
在文件内容中查找值
Find Value in File Contents
问:
我有一个文件中的值列表。我正在尝试读取该文件并查看文件夹中是否存在这些值。如果它们不存在,我只想要一行说它不存在,这样我就可以把它放到 csv 中并处理丢失的文件。
我正在用 Python 做这件事。
到目前为止,我已经能够让它读取文件,但它并没有像我想要的那样将输出写入文件。
这是我目前所拥有的。
import os
import re
# Get the list of files in the directory
files = os.listdir("W:\JA\JA's Coding Curiosity\Python\Test Folder\Test Files")
# Create a list of values to check for
with open("W:\JA\JA's Coding Curiosity\Python\Test Folder\Values.txt", 'r') as f:
my_list = f.readlines()
list_without_newline = [line.strip() for line in my_list]
# Check if each value exists in any of the files
for value in list_without_newline:
if any(value in file for file in files):
with open("W:\JA\JA's Coding Curiosity\Python\Test Folder\Results.txt",'w') as f:
f.write("is\\T{}\\T{}\n".format(value, files[files.index(value)]))
else:
with open("W:\JA\JA's Coding Curiosity\Python\Test Folder\Results.txt",'w') as f:
f.write("not\\T{}\\T{}\n".format(value, files[files.index(value)]))
这是我得到的
PS W:\JA\JA's Coding Curiosity\Python\Test Folder> python FileSearch.py
Traceback (most recent call last):
File "W:\JA\JA's Coding Curiosity\Python\Test Folder\FileSearch.py", line 19, in <module>
f.write("not\\T{}\\T{}\n".format(value, files[files.index(value)]))
^^^^^^^^^^^^^^^^^^
ValueError: '12919031' is not in list
我还尝试将文件夹移动到我的 C 盘,但没有任何反应。
答: 暂无答案
评论
files
并且是问题所在。 是路径列表,是 中的字符串。它们大概不会重叠,在这种情况下,你发生了,你遇到了那个错误value
files
value
my_list
else
write()
files[files.index(value)])
recursion
any(value in file for file in files)
查找具有子字符串的文件名。但寻找的是完整的匹配项,而不是子字符串。value
files.index(value)
else
value
files