The following code shows that IndexError: list index out of range
Here i am trying to find a string which starts from "From" and then print the word next to it using .split()
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for a in fh:
a=a.rstrip()
b=a.split()
if b[0]=="From":
count=count+1
print(b[1])
print("There were", count, "lines in the file with From as the first word")
for the following line
if b[0]=="From":
Where am i going wrong?
Validate the length before accessing the index of array.
if len(b) > 0 and b[0] == 'From':
Also make sure to close the file that is opened.
fh.close()
well the problem is if a is empty a.strip will return nothing so you need to check for if a != "" and you should be good
Related
I have started my code and am on at a very good start, however, I have come to a road block when it comes to adding sum, average, minimum, and maximum to my code, I'm sure this is a pretty easy fix to someone who knows what there are doing. Any help would be greatly appreciated. The numbers in my file are 14, 22, and -99.
Here is my code so far:
def main ():
contents=''
try:
infile = openFile()
count, sum = readFile(infile)
closeFile(infile)
display(count, sum)
except IOError:
print('Error, input file not opened properly')
except ValueError:
print('Error, data within the file is corrupt')
def openFile():
infile=open('numbers.txt', 'r')
return infile
def readFile(inf):
count = 0
sum = 0
line = inf.readline()
while line != '':
number = int(line)
sum += number
count += 1
line = inf.readline()
return count, sum
def closeFile(inF):
inF.close()
def display(count, total):
print('count = ', count)
print('Sum = ', total)
main()
In the while line!=' ': statement, it will iterate one-one single element in the file, i.e. it will add 1+4 and break the loop when we get " " according to your example. Instead, you can use .split() function and use for loop. Your code (Assuming that all numbers are in a single line):
def read_file():
f=open("numbers.txt","r")
line=f.readline()
l=[int(g) for g in line.split(",")] #there should be no gap between number and comma
s=sum(l)
avg=sum(l)/len(l)
maximum=max(l)
minimum=min(l)
f.close()
return s, avg, maximum, minimum
read_file()
Your code contains a number of antipatterns: you apparently tried to structure it OO-like but without using a class... But this:
line = inf.readline()
while line != '':
number = int(line)
sum += number
count += 1
line = inf.readline()
is the worst part and probably the culprit.
Idiomatic Python seldom use readline and just iterate the file object, but good practices recommend to strip input lines to ignore trailing blank characters:
for line in inf:
if line.strip() == '':
break
sum += number
count += 1
word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
for line in file1:
index += 1
if word in line:
flag = 1
break
if flag == 0:
print(word + " not found")
else:
#I would like to print not only the line that has the string, but also the previous and next lines
print(?)
print(line)
print(?)
file1.close()
Use contents = file1.readlines() which converts the file into a list.
Then, loop through contents and if word is found, you can print contents[i], contents[i-1], contents[i+1]. Make sure to add some error handling if word is in the first line as contents[i-1] would throw and error.
word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
previousline = ''
nextline = ''
for line in file1:
index += 1
if word in line:
finalindex = index
finalline = line
flag = 1
elsif flag==1
print(previousline + finalline + line)
print(index-1 + index + index+1)
else
previousline = line
You basically already had the main ingredients:
you have line (the line you currently evaluate)
you have the index (index)
the todo thus becomes storing the previous and next line in some variable and then printing the results.
have not tested it but code should be something like the above.....
splitting if you find the word, if you have found it and you flagged it previous time and if you have not flagged it.
i believe the else-if shouldnt fire unless flag ==1
wordlist = open(r'C:\Users\islam\Desktop\10k most passwords.txt')
for words in wordlist:
line = (words.split())
for count, ele in enumerate(wordlist, 1):
x=(([count, ele]))
print(x)
The output :
[9994, 'hugohugo\n']
[9995, 'eighty\n']
[9996, 'epson\n']
[9997, 'evangeli\n']
[9998, 'eeeee1\n']
[9999, 'eyphed']
How could I find index 0 by typing its content , like input 9995 and the output be :
[9995, 'eighty\n']
This is one approach:
with open('path/to/file') as file:
data = file.readlines()
while True:
try:
user_input = int(input('Enter index:'))
if user_input < 1:
raise ValueError
print(data[user_input - 1].strip())
except (ValueError, IndexError):
print('Invalid index value')
I would say pretty simple since if You split by readlines it already is a list and can be accessed using indexes (subtract 1 to "start" index from 1), the rest of the code that includes error handling is for user convenience.
Simply for getting a value from a "hardcoded" index:
with open('path/to/file') as file:
data = file.readlines()
index = 5
print(data[index - 1])
you can try this:
list.index(element, start, end)
element - the element to be searched
start (optional) - start searching from this index
end (optional) - search the element up to this index
At the place of list you write your list name.
I think this may help
I am currently struggling with a question related to Python File I/O. The question I that I fail to be able to complete is this:
Write a function stats() that takes one input argument: the
name of a text file. The function should print, on the screen, the
number of lines, words, and characters in the file; your function
should open the file only once.
I must also eliminate all puncuation to properly get all of the words.The function should print like so:
>>>stats('example.txt')
line count: 3
word count: 20
character count: 98
Please review the Python documentation about I/O here, Built-in Functions here, and Common string operations here.
There are many ways to get this done. With a quick go at it, the following should get the job done based on your requirements. The split function will eliminate spaces when it converts each line to a list.
def GetFileCounts(in_file):
char_count = 0
word_count = 0
line_count = 0
with open(in_file) as read_file:
for line in read_file:
line_count += 1
char_count += len(line)
word_count += len(line.split(' '))
print "line count: {0}\nword count: {1}\ncharacter count: {2}".format(line_count, word_count, char_count)
You may want to refine your requirements defintion a bit more as there are some subtle things that can change the output:
What is your definition of a character?
only letters?
letters, spaces, in word punctuation (e.g. hyphens), end of lines, etc.?
As far as your question goes,you can achieve it by:
fname = "inputfile.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
There are lots of free tutorial online for python. Please refer those throughly. You can find reference books here
Are you open to third party libs?
Have a look at: https://textblob.readthedocs.org/en/dev/
It has all of the features you want implemented pretty well.
#nagato , i think yout with num_chars += len(line) you come all from the file , character's and blank space , but thank for your code , i can my to do...
My...
def char_freq_table():
with open('/home/.....', 'r') as f:
line = 0
word = 0
character = 0
for i in f:
line = len(list('f'))
word += len(i.split())
character = i.replace(" ", "") #lose the blank space
print "line count: ", line
print "word count: ", word
print "character count: ", len(character) # length all character
char_freq_table()
filename = 'Inputfile.txt'
def filecounts(filename):
try:
f= open(filename)
except IOError:
print("Unable to open the file for reading %s: %s" % (filename))
text = f.readlines()
f.close()
linecount = 0
wordcount = 0
lettercount = 0
for i in text:
linecount += 1
lettercount += len(i)
wordcount += len(i.split(' '))
return lettercount, wordcount, linecount
print ("Problem 1: letters: %d, words: %d, lines: %d" % (filecounts(filename)))
I need some help with finding last element on every row in a textfile that is about 1000rows or more. When they are finded I want to check if they are even integers. If they are I want to add them to "sum". Anyone got an idea in how i can fix this?
fhand = open('textfile.txt')
sum= 0
int(a)
for line in fhand:
a = (line[-1:])
sum = sum + a
print(sum)
Am I on right track? How would you solve it?
Thanks.
Use a try/except:
with open('textfile.txt') as f:
total = 0 # don't use sum as it shadows the builtin sum function
for line in f:
try:
a = int(line.rstrip()[-1]) # get very last character
if a % 2 == 0:
total += a
except ValueError:
pass
print(total)
try this:
with open('textfile.txt') as f:
last_element = [line.split()[-1] for line in f] # when the file is not very large.
total = sum([int(e) for e in last_element if e.isdigit() and int(e) % 2 == 0])
print total