I'm trying to write a program that assigns prices to a list, but I'm having trouble. I keep getting a NameError, that costlist is not defined. The program should ask for an input, append it to the list, and go through the whole list, then write it to the .txt file.
import os
def main():
if os.path.exists("costlist.txt"):
os.remove("costlist.txt")
print ("Assignment 6")
print ()
filename = input("Enter a file name, please. Or enter end to end.")
while filename != "end":
try:
file = open(filename, "r")
listie = file.readlines()
for item in listie:
print(item)
break
except FileNotFoundError:
filename = input("Sorry, that file wasn't found. Try again?")
if filename == "end":
exit
file.close()
listie.sort()
file = open(filename, "w")
for item in listie:
file.write(item.strip("\n"))
file.close()
for item in listie:
cost = input(print( item + "should cost how much?"))
try:
float.cost
except ValueError:
print ("You entered an invalid float that can't convert string to float:" + cost)
print ("Skipping to the next item after" + item)
print (item + "has a cost of" + cost + "dollars")
file = open(costlist.txt, "a")
file.append(cost)
print ("Cost List")
file = open (costlist.txt, "r")
for item in file:
print (item)
print ("Program End")
You forgot to enclose the file name by quotes.
Change file = open(costlist.txt, "a") to file = open("costlist.txt", "a")
And
file = open (costlist.txt, "r") to file = open ("costlist.txt", "r")
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.
it keep stop run after asking the old code and also clear my roti canai file. So what can I do for it.(even is changing all the code)
def modify_roti_canai():
print("\n*-- Modify Roti Canai Menu --*\n")
file = open("roticanai", "r+")
print(file.read())
old_code = input("Enter a Item Code for Modifying (e.g. RC01): ")
if len(old_code) == 4:
new_code = input("New Food Item Code: ")
new_name = input("New Food Item Name: ")
new_price = input("New Food Item Price: ")
file.write(new_code + "," + new_name + "," + new_price + "\n")
else:
print("Item Code Not Existed, Please try again!")
file.close()
*inside my roticanai file is exist few of record:
RC01,ROTI CANAI KOSONG,1.60
RC02,ROTI CANAI SUSU,3.90
RC03,ROTI CANAI CHEESE,4.50
RC04,ROTI CANAI PLANTA,3.90
RC05,ROTI CANAI TISSUE,4.50
s is an empty string. If you are comparing the length(i.e 0) with 4, then if statement evaluates to False. It doesn't add data to "temp.txt" file. It will an empty file renamed as "roticanai".
Rename the filenames as required
**Use the same filename, no need of temp file
def modify_roti_canai():
print("\n*-- Modify Roti Canai Menu --*\n")
with open("test.txt", "r") as file:
#Gets each line of the file as list item
data = [line.rstrip() for line in file.readlines()]
print(data)
#separates codes from data
codes= [x.split(',')[0] for x in data]
print(codes)
old_code = input("Enter a Item Code for Modifying (e.g. RC01): ")
if len(old_code) == 4:
#removes the old code line from data using the index of entered code
data.pop(codes.index(old_code))
new_code = input("New Food Item Code: ")
new_name = input("New Food Item Name: ")
new_price = input("New Food Item Price: ")
new_data = f"{new_code},{new_name},{new_price}"
#appends new data to the data list
data.append(new_data)
#Writes the data list to file
with open('test.txt','w') as file:
for e in data:
file.write(e + '\n')
print(file.read())
else:
print("Item Code Not Existed, Please try again!")
I want to make a limit (say three times) to the attempts when trying to open file and the file cannot be found.
while True:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
except FileNotFoundError:
print ('File does not exist')
print ('')
else:
break
The result of the code above, there is no limit. How can I put the limit in the above codes.
I am using python 3.5.
Replace while True: by for _ in range(3):
_ is a variable name (could by i as well). By convention this name means you are deliberately not using this variable in the code below. It is a "throwaway" variable.
range (xrange in python 2.7+) is a sequence object that generates (lazily) a sequence between 0 and the number given as argument.
Loop three times over a range breaking if you successfully open the file:
for _ in range(3):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
break
except FileNotFoundError:
print ('File does not exist')
print ('')
Or put it in a function:
def try_open(tries):
for _ in range(tries):
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename, "r", newline='')
return inputfile
except FileNotFoundError:
print('File does not exist')
print('')
return False
f = try_open(3)
if f:
with f:
for line in f:
print(line)
If you want to use a while loop then the following code works.
count = 0
while count < 3:
inputfilename = input('Type the filename then press enter: ')
try:
inputfile = open(inputfilename,"r", newline='')
count += 1
except FileNotFoundError:
print ('File does not exist')
print ('')
I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.
Why does this create the file but not write the code into it?
import os
#List for text
mainlist = []
#Definitions
def main():
print("Please Input Data(Type 'Done' When Complete):")
x = input()
if x.lower() == 'done':
sort(mainlist)
else:
mainlist.append(x)
main()
def sort(mainlist):
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?:")
filename = input()
with open(filename + ".txt", "w") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
The file is made, and the data is stored... But finalstring's content isn't written into it. The file remains blank.
You're calling sort(mainlist) multiple times and the file is being overwritten each time. Change the open mode to a like:
with open(filename + ".txt", "a") as f:
f.write(str(finalstring))
See http://docs.python.org/3.2/tutorial/inputoutput.html#reading-and-writing-files