so the code is pretty simple, if the user doesn't enter a viable file then the program shuts down, however when I'm trying to move the opened files from the open_file() function to the main function, then use it in a read_file() function. However it's printing out more than just the first line when i go to print it to test it... im just trying to grab the 4th word separated by commas on the 2nd line.
#opens the file for data
def open_file():
input_file = input("Enter a food crop file: ")
try:
f1 = open(input_file,"r")
next(f1)
except FileNotFoundError:
print("File not found; terminating program.")
return False,False
input_file2 = input("Enter a non-food crop file: ")
try:
f2 = open(input_file2,"r")
next(f2)
except FileNotFoundError:
print("File not found; terminating program.")
return False,False
return f1,f2
def read_files(f1,f2):
line1 = f1.readline()
list_line1 = line1.replace(',','').split()
product1 = list_line1[3]
line2 = f2.readline()
list_line2 = line2.replace(',','').split()
product2 = list_line2[3]
print(product1,product2)
return product1,product2
#main fucntion, will call all other functions
def main():
f1,f2 = open_food_file()
while f1 != False:
product1,product2 = read_files(f1,f2)
#launches code
main()
It should look like this
Enter a food crop file: file_name.csv
Enter a non-food crop file: file_name.csv
product1 = 4th item in list for file1 here
product2 = 4th item in list for file2 here
it returns this, but then it errors out with
File "C:/COLLEGE/CSE/CSE 231/Code/redo.py", line 28, in read_files
product1 = list_line1[3]
IndexError: list index out of range
Related
So I've written a simple program that allows user to enter a line they would like to edit and text they would like to put into that line
def edit_line(file):
a_file = open(file, 'r')
list_of_lines = a_file.readlines()
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
edit_line('sample.txt')
When I run the program it works fine. However, It asks the user to input the text first and the line number second.
What is the reason for this and how can I fix it?
If you want to fix the problem, just split the one line into two:
Instead of:
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
Do:
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
And as the answer #Guy linked explains, when you are doing an assignment line of code, the right hand (value of the variable) is run before the left side.
Validation is everything! What would happen if the user's input for the line number wasn't within the range of lines read from the file?
Here's a more robust approach:
def edit_line(filename):
with open(filename, 'r+') as file:
lines = file.readlines()
while True:
try:
lineno = int(input('What line would you like to edit: '))
if 0 <= lineno < len(lines):
lines[lineno] = input('Write your text here: ') + '\n'
file.seek(0)
file.writelines(lines)
file.truncate()
break
else:
raise ValueError('Line number out of range')
except ValueError as e:
print(e)
edit_line('edit.txt')
Im trying to replace a cetain element in a txt file.
let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber.
let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.
def change_number():
while True:
try:
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
datafile = open('telephonelist.txt')
if name in open('telephonelist.txt').read():
for line in datafile:
if line.strip().startswith(name):
line = line.replace(name,newNumber)
print('I found', name)
quit()
else:
print('I could not find',name+',','please try again!\n')
continue
except ValueError:
print('nn')
change_number()
This i telephonelist.txt
Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.
def change_number():
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
with open('telephonelist.txt', 'r+') as file:
data = file.read().splitlines()
data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
file.seek(0)
file.write("\n".join(data))
file.truncate()
change_number()
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
This question already has answers here:
File Sorting in Python
(3 answers)
Closed 6 years ago.
I have a highscore file for a minesweeper game I am creating and each time after it appends with the new scores, I want it to sort per break line.
I am using:
def save_score(score):
name = input("type a name")
file = open("highscores.txt", "a")
file.write("Table: "+str(GRID_TILES)+"x"+str(GRID_TILES)+"\t mode:"+str(Dif)+"\t score:"+str(score)+"\t name:"+str(name)+"\n")
file.close()
Which comes out in this format:
table: 10x10 mode: easy score: 7592 name:Test
table: 5x5 mode: medium score: 2707 name:Test
How can I make it so that after either the file.write or the file.close it sorts the file per line?
I want it to be sorted by table only. It doesn't matter in what order, as long as all the tables that are 7x7 go by those that are also 7x7.
I have tried doing this:
def save_score(score):
name = input("type a name")
file = open("highscores.txt", "a")
file.write("table: "+str(GRID_TILES)+"x"+str(GRID_TILES)+"\t mode: "+str(Dif) +"\t score: "+str(score)+"\t name: "+str(name)+"\n")
file.close()
file = open("scores.txt", "r")
file2 = open("highscores.txt", "w")
file2.writelines(sorted(file, key=lambda line:str(line.split()[0])))
file.close()
file2.close()
I want to keep my code as short as possible, as the entire minesweeper will take up quite some ammount of code.
def save_score(score):
name = input("type a name")
with open("scores.txt", "a") as file:
file.write("table: {}x{}\t mode: {}\t score: {}\t name: {}\n".format(
GRID_TILES, GRID_TILES, Dif, score, name))
with open("scores.txt") as file, open("highscores.txt", "w") as file2:
file2.writelines(sorted(file, key=lambda line: line.split()[1]))
Thanks to Frerich Raabe for supplying me with an answer!
Here is one way:
import shutil
from tempfile import NamedTemporaryFile
def insert_sorted(file_obj, in_line):
flag = False
with NamedTemporaryFile(delete=False, mode="w+") as temp:
try:
val = int(in_line.split()[-2])
except (IndexError, ValueError):
raise Exception("Invalid format")
for line in file_obj:
try:
lineval = int(line.split()[-2])
except (IndexError, ValueError):
print("""following line has an invalid format,\
and gets escaped\n{}""".format(line))
else:
# Write larger score first when we find smaller score
if lineval <= val:
temp.write(in_line)
temp.write(line)
flag = True
break
else:
temp.write(line)
for line in file_obj:
temp.write(line)
# if the score of the in_line is grater than all the lines write it at the trailing.
if not flag:
temp.write(in_line)
return temp
with open(file_name) as f:
in_line = "table: 10x10 mode: easy score: 8592 name:Test"
temp = insert_sorted(f, in_line)
shutil.move(temp.name, file_name)
First, I have my txt file data here as:
51
2
2
49
15
2
1
14
I would like to convert them into a list to do further calculation, however I couldn't do it and I try to print it one by one by using for loop. Then the error message "Attributes error" kept showing up.
def main():
file = str(input("Please enter the full name of the desired file(with extension) at the prompt below: \n"))
print (get_value(file))
def get_value(file):
file_open = open(file,"r")
print (file_open.read())
a = len(file)
print ("Length =",a)
for line in range file_open:
print (line)
main()
def main():
file = str(input("Please enter the full name of the desired file(with extension) at the prompt below: \n"))
print (get_value(file))
def get_value(file):
file_open = open(file,"r")
lsLines = file_open.readlines()
lsLines = [int(x) for x in lsLines if len(x.strip()) > 0]
file_open.close()
return lsLines
main()
EDIT: wrong language.
with open("file.txt") as f:
ints = [int(line) in f.readlines()]