![]() |
Working with files and dictionaries - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Working with files and dictionaries (/thread-5950.html) |
Working with files and dictionaries - OmarSinno - Oct-30-2017 So, txt = open('testfile.txt','r') d= {} numLines = 0 #reading = txt.readlines() read = txt.readline() print(read) for line in txt.readlines(): numLines += 1 #print(numLines) if numLines not in d: d[numLines] = [txt.readline()] print(d)It's giving me the following: I actually want it to count the number of lines, and for example, in line number 1, I want the values of the dictionary to have the contents of the file split into a list.
RE: Working with files and dictionaries - wavic - Oct-30-2017 from collections import defaultdict d = defaultdict(list) for numLines, line in enumerate(txt.readlines(), 1): d['file_content'].append(line) print(num_lines) # gives you the number of the lines # or you can loop over the lines without enumerate and... print(len(d[file_content'])) # gives you the length of the value of type list in 'd' which is the same as the above print |