I'm attempting to use the code below to get the total number of lines in a text file.
totallines = 0
for line in infile:
totallines += 1
It works, and can print the correct number to the shell. However, when I assign the result to:
item = [0]*totallines
I get an AttributeError when forcing the given line into lowercase with:
item[i] = item[i].lower()
Yet, if I remove the line counter, and replace it with the number of lines in the text file. It works perfectly.
How can I fix this?
It sounds like you'd like to convert the lines of the input file to lowercase and store the result in an array. You could do it this way:
with open('myfile.txt', 'r') as infile:
items = [line.lower() for line in infile]
Or (somewhat) equivalently, (This one drops the "\n" at the end of each line):
with open('myfile.txt', 'r') as infile:
items = infile.read().lower().splitlines()
Note: Don't use file
as a variable name, since it overshadows the builtin file
type.