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
Related
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 having trouble reading strings and numbers from a file with a while loop. There are imaginary names with their age and number of siblings in a text file. I want to read the names, the age, and the number of siblings in the text file with a while loop. If you need more information to solve the problem let me know. Help is very appreciated
outfile = open('practice.txt', 'w')
def main():
print('this program will print the name and age of a person')
details()
def details():
choice = input('Would you like to enter your name, age, and number of siblings? Enter Y for yes and N for no: ')
while choice != 'N' and choice != 'n':
name = input('Enter your name: ')
age = input('Enter your age: ')
siblings = input('Enter the number of siblings: ')
outfile.write(name + '\n')
outfile.write(str(age + '\n'))
outfile.write(str(siblings + '\n'))
choice = input('Would you like to continue? Enter Y for yes and N for no: ')
outfile.close()
main()
This code above is the code that allows me to get the information and store it in a text file. The code below is that im working on so i can read from the file.
infile = open('practice.txt', 'r')
line = infile.readline()
while line != '':
line = infile.readline()
age = int(line)
infile.close()
This is what my data file looks like. BELOW
joe
56
2
john
27
5
james
14
3
You're writing each value on a line, then when you read it you're only reading one line. Read each line back as you write them
with open('practice.txt', 'r') as infile:
while True:
name = infile.readline()
if not name:
break
age = int(infile.readline())
siblings = int(infile.readline())
It's ALMOST right, but a few details:
Open infile not as readline(), but just as "", otherwise, it will skip the first line.
Don't test choice for "N" and for "n", just do something like if choice.lower() == "n":.
Also read the siblings, or do something to skip them, otherwise it will confuse the code, as "2" will be read as the line, "john" will be read as the age, but int("john") will spit an error
Since each person takes 3 lines in the file, you need to read 3 lines each time through the loop.
You should also use rstrip() to remove the newlines at the end of each line.
line = infile.readline()
while line:
name = line.rstrip()
line = infile.readline()
age = int(line.rstrip())
line = infile.readline()
siblings = int(line.rstrip())
# ...
# do something with `name`, `age`, and `siblings`
# ...
line = infile.readline()
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 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.
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")