I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.
My code:
while True:
print("-------------")
name=input("Name: ")
age=input ("Age: ")
contInput=input("Continue Input? (y/n) ")
fp.open("test.txt", "a")
fp.write(name+","+age+"\n")
if contInput=="n":
fp.close()
break
else:
continue
with open("test.txt", "r") as fp:
rd = fp.read().split('\n')
????
fp.close()
so I just confuse about file read. I want to print my saved data like below.
name [tab] age
but after used split method, rd type is list.
Can I divide name & age as each items?
fp.open("test.txt", "a")
At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?
You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.
fp.write(name+","+"age"+"\n")
This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")
Try this for your input loop:
with open("test.txt", "r") as fp:
for line in fp:
data = line.split(",")
name = data[0]
age = data[1]
Related
I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.
I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.read()
print(file_contents)
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()
Everytime someone adds their name, I'd like it to become something like this:
Vix
Mike
Valerie
Something similar like that (above) where they have to run the program again to see the Hall of Fame.
Thank you!
I can understand your question. you can try using the JSON module and do something like this.
import json
list = [1, "Vix"]
with open ('HallOfFame.txt', 'w') as filehandle:
json.dump(list, filehandle)
here you can update the list every time you get input. and write it to the text file. but the appearance will look like this.
[1, "Vix"]
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.readlines()
if len(file_contents) != 0:
print("\nHall of Fame")
for line in file_contents:
count += 1
print("{}. {}".format(count, line.strip()))
print()
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()
elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")
I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.
I've created a function and got stuck on it.
Meaning of the function:
User types in a file, number and own name.
Program writes the name at the end of the file 'number' times.
And just prints out contents of the file.
What's the problem?
There are strange characters and a big space under it when program reads the file.
Like this: 圀漀爀氀搀眀椀搀攀㬀 ㈀ 㐀 ⴀ 瀀爀攀猀攀渀琀ഀഀ (and then there is a huge space for 10-15 lines in Powershell)
Error: 'str' object has no attribute 'close'.
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
open_file = open(file_name, 'a+')
listok = []
while len(listok) < enter_1:
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
read_file = open_file.read()
print read_file
file_name.close()
filemania()
I think the problem is somewhere here:
open_file = open(file_name, 'a+')
Does somebody know how to solve these problems?
Firstly you set file_name = raw_input("Type in any text file> ") so you are trying to close a string with file_name.close():
When you write to open_file you move the pointer to the end of the file because you are appending so read_file = open_file.read() is not going to do what you think.
You will need to seek to the start of the file again to print the content, open_file.seek(0).
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
# with automatically closes your files
with open(file_name, 'a+') as open_file:
listok = []
# use range
for _ in range(enter_1):
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
# move pointer to start of the file again
open_file.seek(0)
read_file = open_file.read()
print read_file
filemania()
For your second error, you are trying to close file_name, which is the raw input string. You mean to close open_file
Try that and report back.
def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!
Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'
f = open('test.txt', 'a')
Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"
f.write(sumOfStudent + "\n")