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")
Related
def add():
while True:
try:
a = int(input("How many words do you want to add:"))
if a >= 0:
break
else:
raise ValueError
except ValueError:
print("Not valid ")
return a
for i in range(add()):
key_i = input(f"Turkish meaning: {i + 1}: ")
value_i = input("translated version: ")
with open('words.txt', 'a+') as f:
f.write("'"+key_i+':')+ f.write(value_i+"'"+",")
My goal is to create my own dictionary,but I am adding a list into the txt file, so it is added into the txt file like this
words = {'araba:kol',
but when I search the txt file it gives me the whole list
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('words.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
What can I do to make it output like this
car:araba
Use JSON module to avoid having to write the dictionary line by line yourself.
import json
with open('words.json', 'a+') as f:
json.dump({key_i: value_i}, f)
with open('data.json', 'r') as f:
d2 = json.load(f)
d2 is now the data that you wrote to the file.
Note, that you should change the a+ to 'w' as you only have one dictionary per file.
If that string input by User exists in text file, the program should find/return line number in text file and print the line number
kw is the user input btw
some code for reference:
def DELITEM():
kw = Dele.get()
with open('notify.txt') as f:
if kw in f.read:
print('the number of the line kw is in')
I guess you could do something like:
with open('notify.txt', 'r') as f:
for num, line in enumerate(f):
if kw==line:
print(num)
Here enumerate() adds a counter to the file that allows you to identify lines.
you could loop through the lines until you find it with readlines
DELITEM():
kw = Dele.get()
with open('notify.txt', 'r') as f:
if kw in f.read:
lines = f.readlines()
for i in range(len(lines)):
if kw in lines[i]:
print("The line is",i)
break
To delete the line from the text file, on way would be to delete the line in the list then write the lines back onto the file. So something like this
del lines[i]
then have another with where you write
with open('notify.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
so putting this altogether you have
DELITEM():
lines = []
kw = Dele.get()
with open('notify.txt', 'r') as f:
if kw in f.read:
lines = f.readlines()
for i in range(len(lines)):
if kw in lines[i]:
print("The line is",i)
del lines[i]
break
with open('notify.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
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.
I am trying to insert a file and I keep getting a syntax error on the line line = infile.redline()
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Enter the name of the file: ')
# Open the specified file for reading
infile = open('test.txt', 'r')
# Priming read
line = infile.redline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rtrip('\n')
print(line)
1ine = infile.readline()
# Update counter when line is read
counter +=1
# Close file
infile.close()
# Call the main function.
main()
rtrip should be rstrip. redline should be readline. infile.close() should be indented, and main() should not be.
However, the most serious problem is here:
1ine = infile.readline()
That first character is a one, not an L.
Knowing the standard libraries can make your life much simpler!
from itertools import islice
def main():
fname = input('Enter the name of the file: ')
with open(fname) as inf:
for line in islice(inf, 5): # get the first 5 lines
print(line.rstrip())
if __name__=="__main__":
main()
It is not redline but readline:
line = infile.redline()
Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ???
import re
file = open("text.txt","r")
text = file.readlines()
file.close()
line_count=0
for line in text:
User_Input_list[] += [] + line.split()
line_count += 1
the problem seems to be on the second last line with the declaration of the list
Do it like this:
input = []
line_count = 0
with open("text.txt","r") as file:
for line in file:
input.extend(line.split())
line_count += 1
Why not
UserInputList += line.split()?
If you want each line in the file to be a separate element in the list, here's a simpler way to do it:
import re
file = open("text.txt","r")
text = file.readlines()
file.close()
line_count=0
line_list = []
for line in text:
line_list.append(line)
line_count += 1
Or using list comprehension:
import re
file = open("text.txt","r")
text = file.readlines()
file.close()
line_list = []
[line_list.append(a_line) for a_line in text]
line_count = len(line_list)