This question already has answers here:
Correct way to write line to file?
(17 answers)
Closed 6 years ago.
I'm trying to write some text to a file, and here's what i tried :
text = "Lorem Ipsum is simply dummy text of the printing and typesetting " \
"industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
" when an unknown printer took a galley of type and scrambled it to make a type specimen book."
target = open("file", 'wb')
target.writelines(text)
And I get an empty file.
How can I do this?
This is how to print to a txt file:
file = open("Exported.txt", "w")
file.write("Text to write to file")
file.close() #This close() is important
Another way to do so would to be:
with open('Exported.txt', 'w') as file:
file.write("Text to write to file")
This is a program I made to write a txt file:
import os.path
def start():
print("What do you want to do?")
print(" Type a to write a file")
print(" Type b to read a file")
choice = input(" -")
if choice == "a":
create()
elif choice == "b":
read()
else:
print("Incorrect spelling of a or b\n\n")
start()
def create():
print()
filename = input("What do you want the file to be called?\n")
if os.path.isfile(filename):
print("This file already exists")
print("Are you sure you would like to overwrite?")
overwrite = input("y or n")
if overwrite == "y":
print("File has been overwritten")
write(filename)
else:
print("I will restart the program for you")
elif not os.path.isfile(filename):
print("The file has not yet been created")
write(filename)
else:
print("Error")
def write(filename):
print()
print("What would you like the word to end writing to be?")
keyword = input()
print("What would you like in your file?")
text = ""
filename = open(filename, 'w')
while text != keyword:
filename.write(text)
filename.write("\n")
text = input()
def read():
print()
print("You are now in the reading area")
filename = input("Please enter your file name: -")
if os.path.isfile(filename):
filename = open(filename, 'r')
print(filename.read())
elif not os.path.isfile(filename):
print("The file does not exist\n\n")
start()
else:
print("Error")
start()
writelines expects an iterable (e.g. a list) of lines, so don't use that. And you need to close the file to save the changes, which is best done with a with statement:
with open("file", 'wb') as target:
target.write(text)
The code you've provided produces a file named file with the desired lines. Perhaps you meant to save it as "file.txt". Also, the 'b' in the 'wb' flag tells the code to write the file in binary mode (more information here). Try just using 'w' if you want the file to be readable.
Finally it is best practice to use the with statement when accessing files
text ="Lorem Ipsum is simply dummy text of the printing and typesetting " \
"industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
" when an unknown printer took a galley of type and scrambled it to make a type specimen book."
with open("file.txt", 'w') as f:
f.write(text)
By this way you should close the file directly:
target = open("filename.txt", 'w')
target.writelines(text)
target.close()
By this way the file closed after the indented block after the with has finished execution:
with open("filename.txt", "w") as fh:
fh.write(text)
See here for more info.
Related
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.
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")