`File = input("Please enter the name for your txt. file: ")
fileName = (File + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
fileName.append(name)
fileName.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
file = open(fileName, mode = WRITE)
file.write(name)
file.close()
print("file written successfully.")
`
I am just practicing to write the file in Python, but something bad happened. Please help me. Thank you.
The code.
The error description.
Here are still some errors about this :
fileName.remove("DONE")
Still showing 'str' error.
THANK YOU
You try to append to string which is not correct in Python, instead try:
filename += 'name'
You're trying to build a list of names. Start with a list:
guests = []
and then append the values provided by your user:
while name is not "Done":
prompt = "Please input the name of the next guest, or 'Done'."
guests.append(input(prompt).upper())
then you can sort that list and write the values to the file. (which you seem to have a handle on)
Appending the guests' names to fileName, or concatenating them onto it, wouldn't make a lot of sense. You'd end up with something like "data.txtJOEBOBJANELINDA" which would do you no good at all.
Related
everyone. I have a Python assignment that requires me to do the following:
Download this CSV fileLinks to an external site of female Oscar winners (https://docs.google.com/document/d/1Bq2T4m7FhWVXEJlD_UGti0zrIaoRCxDfRBVPOZq89bI/edit?usp=sharing) and open it into a text editor on your computer
Add a text file to your sandbox project named OscarWinnersFemales.txt
Copy and paste several lines from the original file into your sandbox file. Make sure that you include the header.
Write a Python program that does the following:
Open the file and store the file object in a variable
Read the entire contents line by line into a list and strip away the newline character at the end of each line
Using list slicing, print lines 4 through 7 of your file
Write code that will ask the user for an actress name and then search the list to see if it is in there. If it is it will display the record and if it is not it will display Sorry not found.
Close the file
Below is the code I currently have. I've already completed the first three bullet points but I can't figure out how to implement a search function into the list. Could anyone help clarify it for me? Thanks.
f = open('OscarsWinnersFemales.txt')
f = ([x.strip("\n") for x in f.readlines()])
print(f[3:7])
Here's what I tried already but it just keeps returning failure:
def search_func():
actress = input("Enter an actress name: ")
for x in f:
if actress in f:
print("success")
else:
print("failure")
search_func()
I hate it when people use complicated commands like ([x.strip("\n") for x in f.readlines()]) so ill just use multiple lines but you can do what you like.
f = open("OscarWinnersFemales.txt")
f = f.readlines()
f.close()
data = {} # will list the actors and the data as their values
for i, d in enumerate(data):
f[i] = d.strip("\n")
try:
index, year, age, name, movie = d.split(",")
except ValueError:
index, year, age, name, movie, movie2 = d.split(",")
movie += " and " + movie2
data[name] = f"{index}-> {year}-{age} | {movie}"
print(f[3:7])
def search_actr(name):
if name in data: print(data[name])
else: print("Actress does not exist in database. Remember to use captols and their full name")
I apologize if there are any errors, I decided not to download the file but everything I wrote is based off my knowledge and testing.
I have figured it out
file = open("OscarWinnersFemales.txt","r")
OscarWinnersFemales_List = []
for line in file:
stripped_line = line.strip()
OscarWinnersFemales_List.append(stripped_line)
file.close()
print(OscarWinnersFemales_List[3:7])
print()
actress_line = 0
name = input("Enter An Actress's Name: ")
for line in OscarWinnersFemales_List:
if name in line:
actress_line = line
break
if actress_line == 0:
print("Sorry, not found.")
else:
print()
print(actress_line)
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: ")
So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)
'Application1': ['Username1', 'Password1']
'Application2': ['Username2', 'Password2']
So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)
hp = open("Passwords.txt","a") #open the file
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ") #make variables to add
hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file
hp.close() #close the file
I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?
As said in a different answer the problem is your string handling when writing to the file. I would recommend to use string formatting:
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
See https://pyformat.info/
Recommended code:
# Ask for variables to add
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ")
# Open file
with open("Passwords.txt", "a") as hp:
# Add line with same format as the rest of lines
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
If you use the with open(...) as ...: you don't have to call the close method, it's called automatically when you exit the with's scope.
Your problem is when you try to write to the file. Change it to
hp.write('\n\'' + key + '\': ''[\'' + usr + '\', ' '\'' + psw +'\']')
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.
I want the text to display the users name if they have entered it before. I have this working in c++ but wanted to practice python. the output will continue to do the "else" statement. I have tried having the if statement search for a string such as "noname" or "empty" and it would still do the else statement.
fr = open('sample.txt','r')
name = fr.read()
fr.close()
if name is None:
fw = open('sample.txt','w')
stuff = raw_input("enter name:")
fw.write(stuff)
fw.close()
else:
print(name)
If you have a blank file without any data in it, f.read() doesn't return None, it returns an empty string.
So rather than do if name is None you could write if name == '' or, to be certain, if name in (None, '').
You might also want to make sure you add a newline character when you write the names to your file, so you should do:
f.write(name + '\n')
for example.
Edit: As Cat Plus Plus mentioned, you can just do if name:, because both None and an empty string will evaluate to False. I just thought it was less clear for this particular question.
Use with to open files, it closes them automtically:
with open('sample.txt','a+') as names: # if file does not exist, "a" will create it
lines = names.read()
if lines: # if file has data
print("Hello {}".format(lines))
else: # else file is empty, ask for name and write name to file
name = raw_input("enter name:")
names.write(name)
To check if the name exists before writing:
with open('sample.txt','a+') as names:
lines = names.read()
name = raw_input("enter name:")
if name in lines:
print("Hello {}".format(name))
else:
names.write(name)