python - 如何打开文本文件并查找一行中特定单词之后写的内容并将该文件名附加到 Python 中的列表中
问题描述
我正在尝试在 Python 中构建一个应用程序,该应用程序将打开一个文件,并找到一个特定的关键字并仅在该行中读取该关键字之后的内容。如果该值与输入列表中的任何元素匹配,则应将所述文件名(带有扩展名;在本例中为 text.txt)附加到另一个列表中。
这是我的代码:
input_list=input("> ").split(", ") # The input list
file_list=[] # Where the filenames should be appended
with open("/path/to/file.txt") as current_file:
for line in current_file:
if line[5::] in input_list:
print("It works!")
file_list.append(current_file)
elif line[9::] in input_list:
print("It works!")
elif line[12::] in input_list:
print("It works!")
else:
print("It doesn't work!")
但总是打印它不起作用。即使有比赛。更不用说将文件名附加到列表中了。
示例文件:
Value=@3a
Execute=abc
Name=VMTester #line[5::] should remove the "Name=" and also Name could also be "Name[en_us]=" or just "Name[bn]="
Comment=This is a samplefile
样本输入:
VMTester
解决方案
您的代码原则上看起来不错;只是file_list
如果你这样做,你将一个文件对象附加到你的file_list.append(current_file)
. 上下文甚至会关闭它,with
所以没有必要这样做......此外,您可以使用它any
来检查是否有任何input_list
项目是in
当前的line
. 假设一旦遇到匹配就停止搜索,您可以使用break
跳过所有其他行。您的代码的修改版本可能看起来像
input_files = ["/path/to/file.txt"] # you can add more files to search here...
input_list = input("> ").split(", ")
file_list = []
extracted_words = []
for file in input_files: # added loop through all files to search
with open(file, 'r') as current_file:
for line in current_file:
if any(w in line for w in input_list):
print("It works!")
# append the file name:
file_list.append(file)
# append the matched word (strip newline character):
extracted_words.append(line.split('=')[1:][0].strip())
break
print("It doesn't work!") # looped through all lines, no match encountered
推荐阅读
- python - ModuleNotFoundError:Jupyter Notebook 上没有名为“pandas”的模块
- html - 使用创建 html 表
- r - 在 R studio 中将图形作为元文件复制到剪贴板时,如何提高 R 制作的图形的质量?
- perl - 为外部命令结果中的值分配键
- c# - RSS 提要 - 使用 WriteTo 更新现有的 TextSyndicationContent
- unity3d - Unity 镜像未正确导入
- python - python烧瓶应用程序中的版本控制
- java - 如何处理:循环调用'Thread.sleep()',可能是忙等待
- c - 读取没有 readdir 的目录
- angular - Angular 模板抱怨 c_r1.getCatType 不是函数