Python Forum

Full Version: Working with files and dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:
Output:
{1: [''], 2: [''], 3: ['']}
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.
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