How to find files with a string
Brian Oney
brian.j.oney at googlemail.com
Wed Jan 9 12:08:47 EST 2019
On Wed, 2019-01-09 at 08:29 -0800, anton.gridushko at gmail.com wrote:
> Hello everyone!
>
> I need to find a file, that contains a string TeNum
>
> I try to
>
> 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()
>
> But there are mistakes like
> 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
>
> Could you help me to solve this thread?
the error message is somewhat clear. You need to add a key-value pair to
a dictionary. You may consider changing 'res' to a 'list'. You then need
to 'append'.
Either way, 'find_value' will return the filename regardless of whether
the value is present or not. That should get you started.
More information about the Python-list
mailing list