我需要找到包含字符串“ TeNam”的文件的所有名称:
import os
import sys
def find_value(fname):
value = 0
with open(fname, encoding='cp866') as fn:
try:
for i in fn:
if 'TeNam' in i:
print(fname)
except IndexError:
pass
return {fname}
def main():
dirname = ('H:\1\3')
os.chdir(dirname)
res = {}
for i in os.listdir(dirname):
res.update(find_value(i))
print('Filename is: ')
if __name__ == "__main__":
main()
但是,有一个错误:
C:\Users\Anton\AppData\Local\Programs\Python\Python36-32\python.exe "C:/Users/Anton/PycharmProjects/Работа с файловой системой/Перебор файлов из папки.py"
Traceback (most recent call last):
File "C:/Users/Anton/PycharmProjects/Работа с файловой системой/Перебор файлов из папки.py", line 21, in <module>
main()
File "C:/Users/Anton/PycharmProjects/Работа с файловой системой/Перебор файлов из папки.py", line 18, in main
res.update(find_value(i))
ValueError: dictionary update sequence element #0 has length 35; 2 is required
Process finished with exit code 1
您能帮我提供代码吗?
答案 0 :(得分:0)
分为3部分:
类似的东西:
def is_file_match(file_name, match_word="bla"):
try:
with open(file__name_path) as f:
file_lines = f.readlines()
return any(match_word in l for l in file_lines) # with case sensitivity
except OSError:
return false
def get_all_files(dir_name):
return filter(is_file_match, os.listdir(dir_name)
res = get_all_files(requested_dir)
答案 1 :(得分:0)
find_value 返回一个 set ([Python 3]: Sets)。
res 是 字典 (不是空的 set -与我一样认为你打算)。其 update 方法([Python 3]: update([other]))无法与提供的 set 一起使用(嗯,除非其 string 元素的长度为2)。
示例:
>>> d = {} >>> type(d) <class 'dict'> >>> t = {"abc"} >>> type(t) <class 'set'> >>> >>> d.update(t) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: dictionary update sequence element #0 has length 3; 2 is required >>> >>> d = set() >>> d.update(t) >>> d {'abc'} >>> type(d) <class 'set'>
从上面可以看到,解决方法是正确初始化 res (作为 set ):
res = set()