How to check if a file is empty? python - python

I have a code that i am writing to read a txt file and report sum, average, ect... but I also need it to recognize when the txt file is empty or has no numbers in it, and not crash. i have tried os.stat(f).st_size == 0, and os.path.getsize(f) == 0:, and reading the first character too. for some reason my code is not picking up on the exception and keeps continuing on with the rest of the code and then crashes when trying to divide by zero to find the average. I am also not using any external libraries.
#the below code asks for the file name and opens the file :)
while (True):
try:
filename = input("What file would you like to acess?: ")
f = open(filename, "r")
except IOError:
print("File", filename, "could not be opened")
except:
if os.path.getsize(f) == 0:
print("There are no numbers in", filename)
else:
break
#the below line displays the file name :)
print("File Name: ", f.name)
#the below code calculates the sum and prints it :)
sum=0
for n in f:
n=n.strip()
sum=sum+int(n)
print("Sum: ", sum)
#the below code calculates the number of lines and prints it :)
with open(filename, "r") as f:
count = 0
for line in f:
if line != "\n":
count += 1
print("Count: ", count)
#the below code calculates the average and prints it :)
avg = sum/count
print("Average: ", avg)

Related

My code cannot find my file, and I am not sure what is wrong with it

def get_file():
file_name = input("Enter the name of the file: ")
try:
count = 0
total = 0.0
average = 0.0
maximum = 0
minimum = 0
range1 = 0
with open(file_name) as file:
number = int(line)
count = count + 1
total = total+ num
maximum = max(number)
minimum = min(number)
average = total/count
range = maximum = minimum
print('The name of the file: ', file_name)
print('The sum of the numbers: ', total)
print('The count of how many numbers are in the file: ', count)
print('The average of the numbers: ', average)
print('The maximum value: ', maximum)
print('The minimum value: ', minimum)
print('The range of the values (maximum - minimum): ', range)
except:
print("The file is not found.")
def main():
get_file()
main()
That is my code, I keep getting the error that the file is not found. I have made sure that the text files that I am inputing into this code is in the same file and that I am spelling everything right. What is wrong
well you are never doing anything with lines of file, and you need to make sure you are passing the right file path syntax to the function \ code. I.E.
def get_file(file_name):
""" do something with file. """
print(file_name, 'what path or file was sent to function?')
try:
with open(file_name) as file:
for line in file:
if line:
print(line)
except FileNotFoundError:
print("Wrong file or file path")
except OSError as err:
print("OS error: {0}".format(err))
print()
def main():
file_one = '\\192.168.1.249\DataDrive_02TB\Tools\net_scanner\hi.txt'
file_three = 'c:\temp\hi.txt'
file_two = '//192.168.1.249/DataDrive_02TB/Tools/net_scanner/hi.txt'
get_file(file_one)
get_file(file_three)
get_file(file_two)
file_input = input("Enter the name of the file: ")
get_file(file_input)
main()

reading and deleting lines in python

I am trying to read all the lines in a specific file, and it prints the number of the line as an index.
What I am trying to do is to delete the line by inputting the number of the line by the user.
As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted.
This is the code of the delete function:
def deleteorders ():
index = 0
fh = open ('orders.txt', 'r')
lines = fh.readlines()
for line in lines:
lines = fh.readlines()
index = index+1
print (str(index) + ' ' + line)
try:
indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))
if indexinp == 'B':
return
else:
del line[indexinp]
print (line)
fh = open ('orders.txt', 'w')
fh.writelines(line)
fh.close()
except:
print ('The entered number is not in the range')
return
This should work (you'll need to add the error handling back in):
lines = enumerate(open('orders.txt'))
for i, line in lines:
print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))

Adding integers from a file

I'm writing a function that sums up integers from a file.
Here's the code:
def sum_integers_from_file(file_name):
try:
file = open(name)
total = 0
for i in file:
total += int(i)
file.close()
return total
except:
print "error"
file foo.txt:
1234
The function returns 1234.
why doesn't total += int(i) add up all the integers?
It is highly recommended to read files in a with statement. That frees you from the responsibility of closing the file and is also shorter! This works:
def sum_integers_from_file(file_name):
try:
with open(file_name, 'r') as f:
s = f.read()
total = 0
for char in s:
total += int(char)
return total
except:
print("error")
Your file has one line.
You're adding all ints from each line.
If you want to add 1,2,3,4 with that method move them to new lines
Also, you can do the same thing with this
with open(name) as f:
return sum(int(line) for line in f)

How to get my python code to go back into the loop after the exception is thrown

I'm a beginner in python & am having some problems with the structure of my homework assignment; my assignment is: "Write a program that asks the user for a filename, opens the file and reads through the file just once before reporting back to the user the number of characters (including spaces and end of line characters), the number of words, and the number of lines in the file.
If the user enters the name of a file that doesn't exist, your program should give her as many tries as she needs in order to type a valid filename. Obtaining a valid filename from the user is a common operation, so start by writing a separate, reusable function that repeatedly asks the user for a filename until she types in a file that your program is able to open."
And, I didn't start that way (& now I'm wondering if with the way I've structured it with "with/as", there's a way to even do that but my problem right now is getting it to go back into the try section of code after the error is thrown (I missed the class where this was explained so I've only ever read about this so I Know I'm not doing something right). I can get it to work as long as it's a filename that exists, if it's not, it prints nothing to the screen. Here's my code:
filename = input("please enter a file name to process:")
lineCount = 0
wordCount = 0
charCount = 0
try:
with open(filename, 'r') as file:
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
except OSError:
print("That file doesn't exist")
filename = input("please enter a file name to process:")
And, I'm not sure what I should do- if I should scrap this whole idea for a simple try: open(filename, 'r') / except: function of it=f there's anyway to salvage this.
So, I thought to fix it this way:
def inputAndRead():
"""prompts user for input, reads file & throws exception"""
filename = None
while (filename is None):
inputFilename = input("please enter a file name to process")
try:
filename = inputFilename
open(filename, 'r')
except OSError:
print("That file doesn't exist")
return filename
inputAndRead()
lineCount = 0
wordCount = 0
charCount = 0
with open(filename, 'r') as file:
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
But, I'm getting error: NameError: name 'file' is not defined
I would reorganize this code so that the file is opened in a loop. No matter how many times the user enters an invalid filename, the code will just ask for a new one and try again.
lineCount = 0
wordCount = 0
charCount = 0
f = None
while f is None:
filename = input("please enter a file name to process:")
try:
f = open(filename)
except OSError:
print("That file doesn't exist")
for line in file:
word = line.split()
lineCount = lineCount + 1
wordCount = wordCount + len(word)
charCount = charCount + len(line)
print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
Write an infinite loop while True. When the file name is correct, at the end of the try, add a break.
Glad that helps

Copy 'N' lines from one file to another in python?

Essentially what I am attempting to do is read 'n' number of lines from a file and then write them to a separate file. This program essentially should take a file that has 100 lines and separate that file into 50 separate files.
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
I do have the file printing as well to show what is in the variable next_n_lines.
*['\n', "randomtext' more junk here\n"]
I would like it instead to look like
randomtext' more junk here
Is this a limitatoin of the islice function? Or am I missing a portion of the syntax?
Thanks for your time!
Where you call str() or print, you want to ''.join(next_n_lines) instead:
print ''.join(next_n_lines)
and
fileout.write(''.join(next_n_lines))
You can store the flattened string in a variable if you don't want to call join twice.
Did you mean something like this?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
or maybe this rough, yet effective code:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2

Categories