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.
Related
So, in my python code I'm supposed to prompt the user for their name, address, and phone number and write that data as a line of comma separated values to the file using the directory and filename. Everything runs except the CSV part.
import os
import csv
def file_system():
"""Display information about users"""
direc = input("Enter name directory to save a file: ")
filename = input("Enter name of the file they want to save to the directory: ")
name = input("Enter your name : ")
address = input("Enter your address : ")
phone_number = input("Enter your phone number : ")
print (direc, filename, name, address, phone_number)
prompt = input()
if os.path.isdir(direc):
writeFile = open(os.path.join(direc,filename),'w')
writeFile.write (direc, + filename)
writeFile.close()
print("File contents:")
readFile = open(os.path.join(direc,filename),'r')
for line in readFile:
print(line)
readFile.close()
if prompt:
with open('Userdata.csv', 'a',
newline='') as outfile:
w = csv.writer(outfile)
w.writerow(name, address, phone_number)
print("File Updated")
else:
print("Directory doesn't exist, please enter again")
file_system()
The issue is with the evaluation of the if statement before the csv section.
run the code below twice, first time just pressing enter, second time typing something and then pressing enter...
prompt = input("input something:\n")
if prompt:
print("you got here")
else:
print("you didn't")
As you can see, when only pressing enter, the if statement becomes False...
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 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]
while True: # Saving a file in txt file
print("Would you like to save the latest generation? ('y' to save): ")
saveInput = input()
if saveInput == 'y' or saveInput == 'Y':
print("Enter destination file name: ")
fileName = input()
try:
open(fileName, "r")
close(fileName)
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()
if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')
elif confirm == 'y':
open(confirm, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
except:
break
This is what i got so far, I'm trying to first read a file take the data from that, and run it through my program and at the end ask if they want to save it, if the file exists ask if they want to overwrite it, and if not create a new one but when i try it skips after you input the destination name like so:
Output
Enter input file name:
g.txt
How many new generations would you like to print?
4
Would you like to save the latest generation? ('y' to save):
y
Enter destination file name:
g.txt
>>>
Can someone help me out? I've been stuck on it for a while
In the code part where you "try" to open the file, the file doesn't exist yet, so it gets to the "except" part (break) and the program terminates.
try:
open(fileName, "r")
close(fileName)
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()
if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')
elif confirm == 'y':
open(confirm, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
except:
break
Replace it with os.path.isfile(fileName)
if os.path.isfile(fileName):
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()
if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')
elif confirm == 'y':
open(**fileName**, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
# if fileName doesn't exist, create a new file and write the line to it.
else:
open(**fileName**, 'w')
for line in new_glider:
confirm2.writelines(new_glider)
print(new_glider)
When you open the file, you need to create a variable to hold that file and write to it.
Right now, you are trying to call writelines on a string, not a file when you do this: confirm2.writelines(new_glider)
Here's how to write to a file properly:
with open(confirm, 'w') as f:
f.writelines(new_glider)
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.