Python Forum
Working with files and dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Working with files and dictionaries
#1
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.
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Question about working with dictionaries Ashcora 13 2,081 Dec-27-2022, 09:09 PM
Last Post: Ashcora
  Working with excel files arsouzaesilva 6 3,195 Sep-17-2021, 06:52 PM
Last Post: arsouzaesilva
Question Working with existing files Gilush 7 3,061 Feb-10-2021, 08:55 PM
Last Post: Gilush
  filecmp is not working for UTF-8 BOM encoded files sureshnagarajan 3 2,620 Feb-10-2021, 11:17 AM
Last Post: sureshnagarajan
  working with more excel files Krszt 1 2,469 Mar-13-2019, 11:41 AM
Last Post: perfringo
  Working with dictionaries and keys netrate 9 5,850 Jun-01-2017, 05:29 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020