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)
Related
I was wondering what I am doing wrong. I'm writing a python program that converts my "joke-made" programming language into python. I always get this weird mess.
This is my code
#input file
inputfile = input("Filename > ")
print("""
Available Languages:
Python
""")
langsel = input("Select > ")
fin = open(f"{inputfile}", "rt")
#output file to write the result to
fout = open(f"{inputfile}.py", "wt")
#for each line in the input file
if langsel == "Python":
for line in fin:
fout.write(line.replace('printiln(', 'print('))
fout.write(line.replace('rinput(', 'input('))
fout.write(line.replace('printiln("', 'print("'))
fout.write(line.replace("printiln('", "print('"))
else:
print("Invalid Language")
#close input and output files
fin.close()
fout.close()
I used this file as a test:
printiln("Are you sure? ")
rinput("Yes or No? ")
Python puts out this file when running the program:
print("Are you sure? ")
printiln("Are you sure? ")
print("Are you sure? ")
printiln("Are you sure? ")
rinput("Yes or No? ")
input("Yes or No? ")
rinput("Yes or No? ")
rinput("Yes or No? ")
I want my output to be:
print("Are you sure? ")
input("Yes or No? ")
You get four output lines per input line because you have four writes in your for block.
for line in fin:
fout.write(line.replace('printiln(', 'print('))
fout.write(line.replace('rinput(', 'input('))
fout.write(line.replace('printiln("', 'print("'))
fout.write(line.replace("printiln('", "print('"))
Make sure you only write a single line for each input line. For example, you can do this.
for line in fin:
line = line.replace('printiln(', 'print(')
line = line.replace('rinput(', 'input(')
fout.write(line) # single write to output file
so I'm currently trying to print a list of cards in a text based card battler I'm making for a school project, and I'm wondering if I can get some help. I'm trying to print something different if a line in a file is 0 or 1, but I can't figure it out. thanks if you can help
def mainfunc():
while i<cardlist:
#if it's zero, do this
print("the card this line represents")
#if it's one, do this
print("locked")
#else, becasue if it's else then you're at the end of the file
print("your deck:")
#print your current deck
print("which card do you want to add?")
print(filelinecount("RIPScards"))
This is what I would do (UPDATED):
# For preventing unwanted behavior if this file ever gets imported in another:
if __name__ == "__main__":
with open(**insert file path here**, 'r') as f:
for line in f:
if line.strip() == "0":
print("the card this line represents")
elif line.strip() == "1":
print("locked")
else:
print("your deck")
print("which card do you want to add?")
print(filelinecount("RIPScards"))
You can read a file line-by-line with it open like so:
with open(**file path**, 'r') as f:
for line in f:
# Do stuff with the line here
Or you can read all the lines one time and close the file, then do stuff with the lines, like so:
f = open(**file name here**, 'r')
$lines = f.readlines()
f.close() # Make sure to close it, 'with open' method automatically does that for you, but manually opening it (like in this example) will not do it for you!
# Do stuff with it:
for line in lines:
# Do something with the line
Hopefully that helps!
I'm trying to write this program where if the user opens an existing file, they have the option to either read, start over, or append to it, but the append option isn't working. Why is that?
from sys import argv
file = input("Please open a file: ")
try:
file = open(file, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "a":
print(file.read())
elif choice in "b":
print("What would you like to write?")
file.write(input())
elif choice in "c":
file = open(file, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())```
The problem with your code is that you are assigning the variable file to the input of the user in input("Please open a file: "), but right after this you assign it to be the txt file in file = open(file, "r+").
So, when you write file = open(file, "a"), the compiler is reading file not as the user input, but the opened txt file.
What you should do is to give different names to the different variables
from sys import argv
filename = input("Please open a file: ")
try:
file = open(filename, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "aA":
print(file.read())
elif choice in "bB":
print("What would you like to write?")
file.write(input())
elif choice in "cC":
file.close()
file = open(filename, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())
UPDATE
As OneLiner said in the comments, you should always close the files after opening them. This can be easily done by using, as he said, with open(filename, "a") as file:. Besides that, I noticed two more things.
First, you shouldn't use except alone, because if I try, for example, to press ctrl+c, it will fall into this exception. What you should write instead is except FileNotFoundError, so that if there is no such file, this exception will be raised.
The second thing I noticed is that you are using the name file as the name of a variable. The problem is that file is already being used in python for another thing, so it would be better to use another name. In that case the code would be:
from sys import argv
filename = input("Please open a file: ")
try:
with open(filename, "r+") as file_txt:
pass
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice == "a":
with open(filename, "r") as file_txt:
print(file_txt.read())
elif choice == "b":
content = input("What would you like to write?\n")
with open(filename, "w") as file_txt:
file_txt.write(content)
elif choice == "c":
with open(filename, "a") as file_txt:
content = input("What would you like to write?\n")
file_txt.write(content)
except FileNotFoundError:
print("This is a new file.\n")
with open(filename, "w") as file_txt:
content = input("What would you like to save in this file?\n")
file_txt.write(content)
Using "r+" allows you to read and write, but the pointer is at the beginning, meaning that "appending" doesn't actually exist. If I'm not mistaken, there's no way to open a file for reading, writing, and appending, because there's no way to move the pointer along the file.
To get around this, I would suggest opening the file separately in each if clause.
If the person wants to read the file, then open it using "r".
If the person wants to write to the file, then open it using "w", and if the person wants to append to it, then open it using "a". More options, such as combinations of two can be found here.
The code:
try:
#removed:
#file = open(file, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "a":
file = open(file, "r")
print(file.read())
elif choice in "b":
file = open(file, "w")
print("What would you like to write?")
file.write(input())
elif choice in "c":
file = open(file, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())
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.