How to find files with a string

Avi Gross avigross at verizon.net
Wed Jan 9 13:33:17 EST 2019


Anton,

OVERVIEW: SET vs DICT

Some of us have less experience decoding Cyrillic error messages. The part we can read suggests the program objected to the way a dictionary was being updated. 

ValueError: dictionary update sequence element #0 has length 35; 2 is required

(The Russian said something like: Working with the file system / Searching files from the .py folder)

The normal method is to provide something that evaluates to a key/value combination. You made an empty dictionary with {} NOT an empty set which is only created using the notation set().

Your find_value() function returns a SET containg the filename unconditionally this way:
	return {fname}

That is not a dictionary entry. It is a set and this is not something you can add to a dictionary as it has no key.

Why the 35 above? I would guess it may be seen as a list of 35 charcaters or something.

Two more points. Your text says searching for TeNum but the function searches for TeNam.

Worse, the function seems to be wrong for the purpose intended. If the goal is to search line by line and if found any number of times, return the filename, it does not do that. It seems to print the filename when any line matches. No idea why you do some other things but the return is unconditional so it should return every filename it finds.

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On Behalf Of anton.gridushko at gmail.com
Sent: Wednesday, January 9, 2019 11:30 AM
To: python-list at python.org
Subject: How to find files with a string

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?
-- 
https://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list