def calculateGrades():
file = open(pickAFile(), "rt")
highestGrade(file)
lowestGrade(file)
def highestGrade (file):
lines= file.readlines()
file.close
len_lines_file = len(lines)
lines = lines[1:len_lines_file]
highest_Grade = 0.0
parts = lines[0].split(",")
highest_Grade = int(parts[2])
for line in lines:
parts = line.split(",")
if int(parts[2]) > highest_Grade:
highest_Grade = int(parts[2])
def lowestGrade(file):
open(file(, "rt")
lines= file.readlines()
file.close()
len_lines_file = len(lines)
lines = lines[1:len_lines_file]
lowest_Grade = 0.0
parts = lines[0].split(",")
lowest_Grade = int(parts[2])
for line in lines:
parts = line.split(",")
if int(parts[2]) < lowest_Grade:
lowest_Grade = int(parts[2])
print lowest_Grade
calculateGrade()
calculateGrade() is what my professor calls the "overlord" function. I am trying to run the file that is pulled in the main function in both the LowestGrade and the highestGrade function but it keeps keeps giving me O/I error and I am not sure what to do.
It seems like the error you have would happen when you try to run lowestGrade() immediately after running highestGrade(). This happens because you have closed the file in highestGrade(), but do not open it correctly in lowestGrade(): the first line in your definition of lowestGrade() should be something like file = open(pickAFile(), "rt").
Often, it is preferable to open files using a with block, e.g.:
with open(pickAFile(), "rt") as file:
lines= file.readlines()
### file.close() is automatically called by Python at the end of the with block
So one option is to remove the open/close lines from the highestGrade and lowestGrade functions, and do it outside, say
def calculateGrades():
with open(pickAFile(), "rt") as file:
highestGrade(file)
lowestGrade(file)
However, you may want to consider using parts as the argument to lowestGrade and highestGrade, and compute it outside the function:
def calculateGrades():
with open(pickAFile(), "rt") as file:
lines= file.readlines()
len_lines_file = len(lines)
lines = lines[1:len_lines_file]
parts = lines[0].split(",")
highestGrade(parts)
lowestGrade(parts)
and truncating the code in highestGrade and lowestGrade as necessary.
Related
I'm creating a program that should create a file (.txt) based on each line of 'clouds.txt'. This is my code:
def CreateFile():
global file_name
f = open(file_name,"w+")
f.write(list_email + ":")
f.close()
def WriteInConfig():
f = open("config/config.txt","a")
f.write(list_name + "\n")
f.close()
with open("clouds.txt","r") as f:
list_lines = sum(1 for line in open('clouds.txt'))
lines = f.readline()
for line in lines:
first_line = f.readline().strip()
list_email = first_line.split('|')[1] #email
print("Email: " + list_email)
list_pass = first_line.split('|')[2] #pass
print("Pass: " + list_pass)
list_name = first_line.split('|')[3] #name
print(list_name)
global file_name
file_name = "config/." + list_name + ".txt"
with open('clouds.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('clouds.txt', 'w') as fout:
fout.writelines(data[1:])
CreateFile()
WriteInConfig()
The clouds.txt file looks like this:
>|clouds.n1c0+mega01#gmail.com|cwSHklDIybllCD1OD4M|Mega01|15|39.91|FdUkLiW0ThDeDkSlqRThMQ| |x
|clouds.n1c0+mega02#gmail.com|tNFVlux4ALC|Mega02|50|49.05|lq1cTyp13Bh9-hc6cZp1RQ|xxx|x
|clouds.n1c0+mega03#gmail.com|7fe4196A4CUT3V|Mega03|50|49.94|BzW7NOGmfhQ01cy9dAdlmg|xxx|xxx >
Everything works fine until 'Mega48'. There I get "IndexError: list index out of range"
>|clouds.n1c0+mega47#gmail.com|bd61t9zxcuC1Yx|Mega47|50|10|Xjff6C8mzEqpa3VcaalUuA|xxx|x
|clouds.n1c0+mega48#gmail.com|kBdnyB6i0PUyUb|Mega48|50|0|R6YfuGP2hvE-uds0ylbQtQ|xxx|x
|clouds.n1c0+mega49#gmail.com|OcAdgpS4tmSLTO|Mega49|50|28.65|xxx| >
I checked and there are no spaces/other characters. As you could see, after creating the file, the program deletes the line. After the error, if I'm starting the program again (and starts from 'Mega47') it doesn't show the error, and everything works as planned.
Any ideas how to fix this?
I see many mistakes in your code. First, what do you want with this list_lines = sum(1 for line in open('clouds.txt'))?
You have a problem in your for loop because you did lines = f.readline() so lines is the first line, then you do for line in lines where line will be each character of the first line and there are more character in the first line than lines in your file to read.
[edited]
you don't need to know the number of lines in the file to do a for loop. You can just do for line in f:, then you don't need to read the line again with readline it is already in the variable line
The function reads the last line of the file at the specified file path. The function returns the last line of the file as a string, if the file is empty it will return an empty string ("").
I tried writing my code like this but it won't work, it's pretty messy and I'm a beginner
def read_last_line(file_path):
with open(file_path, 'r') as file:
size_file = os.path.getsize(file_path)
return_file_empty = " "
last_line = (list(file)[-1])
print(last_line)
if size_file == 0:
return return_file_empty
else:
return last_line
you can use:
def read_last_line(file_path):
with open(file_path) as f:
lines = f.readlines()
return lines[-1] if lines else ''
for big files you may use:
def read_last_line(file_path):
with open(file_path, 'r') as f:
last_line = ''
for line in f:
last_line = line
return last_line
This opens the file and moves though it until there is no more file (raises StopIteration) and returns the last line.
def read_last_line(filename):
line = ""
with open(filename) as fh:
while True:
try:
line = next(fh)
except StopIteration:
return line
You can use a collections.deque to get it like the following. Unlike the currently accepted answer, doesn't require storing the entire file in memory:
from collections import deque
def get_last_line(filename):
with open(filename, 'r') as f:
try:
lastline = deque(f, 1)[0]
except IndexError: # Empty file.
lastline = None
return lastline
print('last line: {}'.format(get_last_line(filename)))
If I've understood the question correctly, something like this maybe?
def get_last_line(file_path):
with open(file_path, "r") as file:
return next(line for line in reversed(file.read().splitlines()) if line)
For opening and reading 1 file even after adding the close argument it is giving the error. The code written is as below:
infilename = "Rate.txt"
infile = open(infilename, "r").readlines()
firstLine = infile.pop(0) #removes the header(first line)
infile = infile[:-1]#removes the last line
for line in infile:
a = line.split()
CheckNumeric = a[4]
CheckNumeric1 = a[5]
strfield = a[3]
infile.close()
By doing infile = open(infilename, "r").readlines() you have actually assigned infile to be a list, rather than an open file object. The garbage collecter should sweep up your open file and close it for you, but a better way to handle this would be to use a with block:
infilename = "Rate.txt"
with open(infilename, "r") as infile:
line_list = infile.readlines()
firstLine = line_list.pop(0) #removes the header(first line)
line_list = line_list[:-1]#removes the last line
for line in line_list:
a = line.split()
CheckNumeric = a[4]
CheckNumeric1 = a[5]
strfield = a[3]
In the code above, everything that is indented within the with block will execute while the file is open. Once the block ends the file is automatically closed.
Value stored in the infile variable is not a file object, it is a list. Because your called readlines method.
Doing
infile = open(infilename, "r").readlines()
you have read the lines of the file and assign the list to infile. But you haven't assigne the file to a variable.
If you want to explicitly close the file:
someFile = open(infilename, "r")
infile = someFile.readlines()
...
someFile.close()
or use with which close the file automatically:
with open(infilename, "r") as someFile:
infile = someFile.readlines()
....
print "the file here is closed"
infile = open(infilename, "r")
# this resp. infile is a file object (where you can call the function close())
infile = open(infilename, "r").readlines()
# this resp. infile is a list object, because readlines() returns a list
That's all.
As #Ffisegydd mentioned above, make use of with statement introduced in in Python 2.5. It will automatically close the file for you after the nested code block. And yet, in case an exception also happened the file will be closed before the exception is caught, pretty handy.
For more info, checkout this out on the context manager:
https://docs.python.org/2/library/contextlib.html
I actually make use of the context manager to achieve somewhat some level of maintainability.
I would use this more memory efficient code:
infilename = "Rate.txt"
with open (infilename) as f:
next(f) # Skip header
dat = None
for line in f:
if dat: # Skip last line
_, _, _, strfield, CheckNumeric, CheckNumeric1 = dat.split()
dat = line
I wrote this code for class and cannot figure out why my lists are not populating with any values. I've tried using a debugger and still can't figure out why it won't work. Any ideas? Also... I know for loops would have made more sense, but I needed to use while loops for the assignment.
__author__ = 'Ethan'
#This program reads in a file from the user which contains lines of
def mileage():
filename = input("Please enter the file name: ")
file = open(filename,"r")
line_list = []
num_lines = sum(1 for line in file)
line_counter = 0
while line_counter <= num_lines:
line = file.readline()
line_items = line.split()
line_list.append(line_items)
line_counter += 1
current_index_pos = 0
while current_index_pos <= num_lines:
current_item = line_list[current_index_pos]
print("Leg",current_index_pos + 1,"---", current_item[0]/current_item[1],"miles/gallon")
current_index_pos += 1
mileage()
This reads to the end of the file
num_lines = sum(1 for line in file)
so there are no lines left to read when you get here
line = file.readline()
Better to structure the code like this
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
line_items = line.split()
line_list.append(line_items)
# after the loop line_counter has counted the lines
or even (if you don't need line_counter)
with open(filename, "r") as fin:
line_list = [line.split() for line in fin]
More advanced would be to use a generator expression or do everything in a single loop to avoid needing to read the whole file into memory at once
def mileage():
filename = input("Please enter the file name: ")
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
current_item = line.split()
print("Leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")
Input.txt File
12626232 : Bookmarks
1321121:
126262
Here 126262: can be anything text or digit, so basically will search for last word is : (colon) and delete the entire line
Output.txt File
12626232 : Bookmarks
My Code:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not ":" in line:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
Problem: When I match with : it remove the entire line, but I just want to check if it is exist in the end of line and if it is end of the line then only remove the entire line.
Any suggestion will be appreciated. Thanks.
I saw as following but not sure how to use it in here
a = "abc here we go:"
print a[:-1]
I believe with this you should be able to achieve what you want.
with open(fname) as f:
lines = f.readlines()
for line in lines:
if not line.strip().endswith(':'):
print line
Here fname is the variable pointing to the file location.
You were almost there with your function. You were checking if : appears anywhere in the line, when you need to check if the line ends with it:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not line.strip().endswith(":"): # This is what you were missing
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
You could have also done if not line.strip()[:-1] == ':':, but endswith() is better suited for your use case.
Here is a compact way to do what you are doing above:
def function_example(infile, outfile, limiter=':'):
''' Filters all lines in :infile: that end in :limiter:
and writes the remaining lines to :outfile: '''
with open(infile) as in, open(outfile,'w') as out:
for line in in:
if not line.strip().endswith(limiter):
out.write(line)
The with statement creates a context and automatically closes files when the block ends.
To search if the last letter is : Do following
if line.strip().endswith(':'):
...Do Something...
You can use a regular expression
import re
#Something end with ':'
regex = re.compile('.(:+)')
new_lines = []
file_name = "path_to_file"
with open(file_name) as _file:
lines = _file.readlines()
new_lines = [line for line in lines if regex.search(line.strip())]
with open(file_name, "w") as _file:
_file.writelines(new_lines)