I'm trying to make a cash machine simulation.
This is my code so far:
print ("Cash Machine\n")
input("Press Enter to begin...")
card_number = int(input("Enter your card number... "))
f = open((card_number + ".txt"),"r")
lines = f.readlines()
x = lines[1]
print(x)
Currently I have a text file called 123 in my folder. Inside the file is how much money the bank account 123 has, but I am having trouble trying to open the file.
Specifically with the line 6. I get an error saying
"No such file or directory: 'card_number.txt'"
How can I make it work?
Thanks
You have to run this program in the same directory that contains the file or use the full path name.
If running in the same directory, you can use the code you have. If not, you can tweak the code like this:
Edit: you are casting your input as an integer when it needs to be a string:
input("Press Enter to begin...")
card_number = input("Enter your card number... ")
f = open(card_number + ".txt","r")
lines = f.readlines()
x = lines[1]
print(x)
Related
I'm not very experienced so please know I'm trying as hard as I can. How do I add the file's first contents (eg. 65) to a new entered number, then overwrite the file to save it?
Any advice is greatly appreciated.
Here is my programming:
henry = 0
emily = 0
george = 0
points = 0
file = open('nfc.txt','r+')
for line in file:
print(line)
if input("Who would you like to give points to? ") == "henry":
points = int(input("How many points would you like to give to Henry? "))
henry = henry + points
print("Henry now has",henry, "points")
points = 0
file.write(str(henry)+" ")
file.write(str(emily)+" ")
file.write(str(george)+" ")
file.close()
else:
print("That name is not valid")
Your code is working when 'nfc.txt' exists in the directory. If the file is not there then use 'w+'. Mind it, if the file already exists then it will overwrite the existing one. Here is the link for more information: https://www.tutorialspoint.com/python3/python_files_io.htm. Also, think about the comment made by ahed87.
I hope, it will help.
p.s: new edit to improve the answer
assuming I understood your question this should do it. it opens the file and gets the values before appending them with user input and writes them to the file. I have commented it in case you get lost I hope this helps.
file = open('nfc.txt', 'r+') ### opens file
f = file.read() ### reads file and assigns it to variable f
f = f.splitlines() ### slits file into list at any neline "\n"
scores = {} ### creates dictionary to store data
for line in f:
line = line.replace(':', '') ### replaces colons with nothing
line = line.split() ### splits name from score
scores[line[0]] = int(line[1]) ###appends dictionary so name is key and score is values
name = input("Who would you like to give points to?").lower() ### user input
if name in scores.keys(): ### checks to see if input is a dict key
point = int(input(
"How many points would you like to give to {}?".format(name))) ### formats name into next input question
scores[name] += point ### adds value to current score
scores['total'] += point ### adds value to change total
file.seek(0) ### sets position in file to start
file.truncate() ### deletes all data in current file
for key in list(scores.keys()): ### gets all keys from dict to ittereate
file.write("{}: {}\n".format(key, str(scores[key]))) ### writes info to file with \n for new person
file.close() ### closes file IMPORTANT
else:
print("That name is not valid")
I do hope you don't mind having to scroll for the comments I know it is not very pythonic
Now it works
You have to use 'w' to write in a file
henry = 0
emily = 0
george = 0
points = 0
file = open('nfc.txt', 'w+')
for line in file:
print(line)
if input("Who would you like to give points to? ") == "henry":
points = int(input("How many points would you like to give to Henry? "))
henry = henry + points
print("Henry now has", henry, "points")
points = 0
file.write(str(henry) + " ")
file.write(str(emily) + " ")
file.write(str(george) + " ")
file.close()
else:
print("That name is not valid")
and in the file you got this
Briefly, I'm testing this code in python:
My idea is to save solut = one + two in a file after inputting the values by keyboard, but now I have a problem. NO message error and nothing is written in file.
python 2.7
I have changed and saved the code and failed and I don't have a backup. I canĀ“t remember how I need to handle an integer and convert in a pointer.
filex = open('test.txt', 'a+')
one = input("first number : \n -> ")
two = input("second number: \n -> ")
solut = one + two
for line in filex:
line = filex.writelines(solut)
filex.close()
Try this:
one = int(input("first number : \n -> "))
two = int(input("second number: \n -> "))
solut = one + two
with open('test.txt', 'a+') as filex:
filex.writelines([str(solut)])
You can use the int() function to convert the string that is input to an integer. Writelines() accepts a list of strings.
If you want to write the variable to a file, use the following code:
with open('test.txt', 'a+') as inputfile:
one = int(raw_input())
two = int(raw_input())
sum = one + two
inputfile.write(str(sum))
I am not able to add a number to my list that i have in a text file and don't know how to.
Code so far:
def add_player_points():
# Allows the user to add a points onto the players information.
L = open("players.txt","r+")
name = raw_input("\n\tPlease enter the name of the player whose points you wish to add: ")
for line in L:
s = line.strip()
string = s.split(",")
if name == string[0]:
opponent = raw_input("\n\t Enter the name of the opponent: ")
points = raw_input("\n\t Enter how many points you would like to add?: ")
new_points = string[7] + points
L.close()
This is a sample of a key in the text file. There are about 100 in the file:
Joe,Bloggs,J.bloggs#anemailaddress.com,01269 512355, 1, 0, 0, 0,
^
The value that i would like this number to be added to is the 0 besides the number already in there, indicated by an arrow below it. The text file is called players.txt as shown.
A full code answer would be helpful.
I didn't like what i wrote earlier, and the use case isn't optimal for fileinput. I took a similar piece of code from the sources and suited it for your needs.
Notice that for each line you modify, you are re-writing an entire file. I strongly suggest changing the way you handle data if performance is a concern.
This code works tho.
from tempfile import mkstemp
from shutil import move
from os import remove, close
def add_player_points():
file_path = "test.txt"
name = raw_input("\n\tPlease enter the name of the player whose points you wish to add: ")
#Create temp file
fh, abs_path = mkstemp()
with open(abs_path,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
stripped_line = line.strip()
split_string = stripped_line.split(",")
print name == split_string[0]
if name == split_string[0]:
opponent = raw_input("\n\t Enter the name of the opponent: ")
points = raw_input("\n\t Enter how many points you would like to add?: ")
temp = int(split_string[5]) + int(points) # fool proofing the code
split_string[5] = str(temp)
stripped_line = ','.join(split_string)# line you shove back into the file.
print stripped_line
new_file.write(stripped_line +'\n')
else:
new_file.write(line)
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
Search and replace a line in a file in Python
Editing specific line in text file in python
You wouldn't expect it to be that big of an issue, but it is.
Another tip: might wanna check the module csv - it might be smarter for file editing than what i showed here.
2 issues, first you're never saving your changes to the file. You need to build the string and then save it at the end with L.write("your new string"). Second, you need to cast the points to ints before adding them, change
new_points = string[7] + points
to
new_points = int(string[7]) + int(points)
Edit: Fixed the syntax as mentioned in the comments
FileName = input("Please enter the name of your text file: ")
APPEND = "a"
WRITE = "w"
File = (FileName + ".txt")
List = []
Name = " "
while Name != "DONE" :
Name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
List.append(Name)
List.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + FileName + " :")
List.sort()
for U in List :
print(U)
File = open(FileName , mode = APPEND)
File.write(U)
File.close()
print("File written successfully.")
Ok guys, I am sorry that I am asking this question over and over, but it annoys me. I don't see any bugs through the code, but the list from the text file ONLY APPEARS ONE NAME. Thanks!
I believe what you are looking for is this:
with open(FileName , mode = APPEND) as f:
for U in List :
print(U)
f.write(U)
f.write("\n")
print("File written successfully.")
using with will allow you to open the file, and python with automatically close it for you should an exception occur while it's in use. You want to open the file before you enter your loop, then append within the loop, and finally, print your success message after closing the file (outside the with). Indentation is important! :)
According to the indentation I see above, you are calling the File open, File write, and File close methods after the loop for U in List. So only the last name will get appended to the file.
(Of course, maybe your indentation is wrong above...)
You're printing the iteration variable 'U' each time, not saving it anywhere. Write the 'U' variable each time to a file and it should work.
I'm writing a program which has the user enter some names and it creates a file with these names. I'm using Python 3.2.
number = eval(input("How many names are there? "))
#Say the user enters 2
outfile = open('names.txt', 'w')
for i in range(number):
name = input("Enter a name >> ")
#Say the user first enters Bob
#Then the user enters Joe
print (name, file=outfile)
outfile.close()
print ("Names have been written to file")
It works but there's one problem. The file that now shows up only reads one line: "Joe". None of the other names appear, only the last one.
You have this code: -
for i in range(number):
name = input("Enter a name >> ")
#Say the user first enters Bob
#Then the user enters Joe
print (name, file=outfile)
You print statment should be inside the loop..
for i in range(number):
name = input("Enter a name >> ")
print (name, file=outfile)
Indentation! As your code is written now, the statement print (name, file=outfile) is executed once, and outside of the loop. So the last time name was set to anything is the one which remains.
To fix this, make sure that statement writing to the file is called right after it is input, and for that to happen, you should indent it as deep as the input statement, to be called as much times as the input is being taken.