I am just a beginner to programming and below is the code that I have written in python to save and edit a file but every time I run the programme it erases the previous save data, so I am confused why it's happening?
filename = raw_input("Please enter the file name to open it:\n")
doc = open (filename,'w')
print doc.read
text_input = raw_input("Please enter the data you want to enter in file:\n")
if text_input == "":
print "no input closing the programme."
else :
doc.write(text_input)
doc.close()
print "Printing the file:\n"
print doc.read
cl_file = raw_input("do you want to truncate file(y/n): ")
if cl_file == "y":
doc.truncate()
else :
print "Wrong input closing notepad"
exit()
You are opening the file in write mode, which truncates the file before writing to it. Instead of using open(filename, 'w') use open(filename, 'a'). The 'a' value tells the open function to use append mode so that writes to the file are added to the end of any existing content.
Related
Hello I am really new to programming and im trying to make like some form-like thing where you input stuff and it gets saved to a text file how do I input the outputs of my code to a text file?
date = input("The Date [Month/Day/Year]: ")
print("")
Name = input("Name: ")
print("")
Age = int(input("Age: "))
print("")
Gender = input("Gender: ")
print("")
Nationality = input("Nationality: ")
p = Age + 10
print(p)
print(date, Name, Age, Gender, Nationality)
I tried adding
sys.stdout = open("test.txt", "w")
(my code here)
sys.stdout.close()
I got from google but instead what it did when I run it is leave the console completely blank. I'll appreciate help, thank you!
By default when your program is printing stuff normally, it prints it to a special file named "stdout" (AKA "standard output", which is your console). The code you got updates stdout to instead reference a file named "test.txt" in write mode (hence the "w"). Therefore, everything you print normally will be rerouted to that new file. There should be a file named "test.txt" in the directory where you are executing your python program, and it should have the output of your program.
Another way of writing to files that I often see is:
with open('test.txt', 'w') as file:
# your code here
# the file will save and close after you exit this block scope
# ex. write:
file.write('hi')
Create a file in which you want to store your information. Collect all your data in a list or dict. I would prefer dict because information is stored systematically. After that, open the file in python in append mode. Remember that your program and your file must be at the exact same location. If not, mention the file location while opening it. I'm recommending append mode because everytime you write, the data should not be lost. If you open in write mode, everytime you write in a file, it writes from starting which may result in losing of data. Now write the dict in the file. Your code:
date = input("The Date [Month/Day/Year]: ")
print("")
Name = input("Name: ")
print("")
Age = int(input("Age: "))
print("")
Gender = input("Gender: ")
print("")
Nationality = input("Nationality: ")
p = Age + 10
print(p)
di={"Date":date,"Name":Name,"Age":Age,"Gender":Gender,"Nationality": Nationality}
print(date, Name, Age, Gender, Nationality)
f=open("test.txt","a")
f.write(di)
f.close()
I'm learning python and trying to delete the contents of a life after the user input. for some reason it deletes the contents of the .txt before it asks for user input. Can't seem to work it out.
from sys import argv
import sys
script, filename = argv
def erase_contents(f):
user_input = input("> ")
if user_input == "yes":
current_file.truncate()
print("successfully deleted")
else:
sys.exit()
current_file = open(filename, "w+")
print(f"Now we are going to erase the contents of {filename}. type yes to delete.")
erase_contents(current_file)
You don't need to use truncate, because you are opening the file using w+ as the mode, which truncates the file immediately. You could use mode a instead, but really, there's no need to open the file at all until you determine that the user wants to truncate the file. You could just write
def erase_contents(fname):
user_input = input("> ")
if user_input == "yes":
with open(fname, "w"):
pass
else:
sys.exit()
print(f"Now we are going to erase the contents of {filename}. type yes to delete.")
erase_contents(filename)
The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)
Question, is there a way to take raw_input from a user and create a text file out of the raw_input? What I mean is say I have a code like this:
def file_make():
name = raw_input("What do you want to name your file? \n")
name_of_file = name + ".txt"
file = open(name_of_file, "r")
file.close()
print name_of_file
file_make()
Could I take there input (EX: TEST) and then create a file called TEST.txt using the variable name? Or is this not possible? I tried searching for this question, but all of my searches pulled up how to take user input and make a text file out of it, which is not what I am trying to do.
You need to have have your open method with write mode in order to write files, assuming the file doesn't exist.
Try
def file_make():
name = raw_input("What do you want to name your file? \n")
name_of_file = name + ".txt"
file = open(name_of_file, "w")
file.close()
print name_of_file
file_make()
You want to open the file in 'a' mode (append), instead of read.
file=open('ClassA1.txt','a')
file=open('ClassB1.txt','a')
file=open('ClassC1.txt','a')
print('hello welcome to maths 2000')
Class=input('please enter your class '+"\n")
name=input('please enter your name '+"\n")
if Class==(int(input"A1")):
file.close('ClassB1')
file.close('ClassC1')
file.write(name+"/n")
file.close
How do I get it to check user input so it can close the files?
Ok first point :
This line:
file=open('ClassA1.txt','a')
opens file 'ClassA1.txt' for appending, assign the file object to the name file (which eventually shadows the builtin type file but that's not relevant here)
Then the second line:
file=open('ClassB1.txt','a')
opens file 'ClassB1.txt' for appending, assign the file object to the name file, sus replacing the binding to the previously opened file "ClassA1.txt". Since there's no other name referencing this previously opened file, it's lost. In the best case, the underlying file pointer will be closed when the object gets garbage-collected (CPython) but this is NOT garanteed by thye language's specification and another implementation might not free the file pointer correctly.
In all cases you can not access 'ClassA1.txt' anymore at this point.
Now the third line:
file=open('ClassC1.txt','a')
does the same thing - reassigning the name file to a new file object etc.
At this point, you have to possibly opened, possibly not, and in both case unreachable (and possibly already garbage collected) file objects and the name file points to the third one - which means any write operation on file will write to file "ClassC1.txt".
If you want to keep all three files opened, you have to keep references to them, either by binding each to a distinct name, ie:
file1=open('ClassA1.txt','a')
file2=open('ClassB1.txt','a')
file3=open('ClassC1.txt','a')
or by storing them in a list:
files = []
files.append(open('ClassA1.txt','a'))
files.append(open('ClassB1.txt','a'))
files.append(open('ClassC1.txt','a'))
so you can now acces them by index, ie files[0], files[1], files[2]
or in a dict:
files = {}
files["A1"] = open('ClassA1.txt','a')
files["B1"] = open('ClassB1.txt','a')
files["C1"] = open('ClassC1.txt','a')
so you can now acces them by key, ie files["A1"], files["A2"], files["A3"]
BUT : why would you
open three files,
ask the user which file he wants to write to,
close the two other files,
write to the selected file
close it
when you could more simply:
ask the user which file he wants to write to,
open it
write to it
close it
Since your files are named after the class name, you can easily build the filename from the class name:
cls = input("please enter your class\n")
filename = "Class{}.txt".format(cls)
f = open(filename, "a")
f.write("whatever")
f.close()
or even more safely (this will ensure the file WILL be closed whatever happens):
cls = input("please enter your class\n")
filename = "Class{}.txt".format(cls)
with open(filename, "a") as f:
f.write("whatever")
Note that in this case you don't have to call f.close()
A couple other points:
Class=input('please enter your class '+"\n")
=> 'cls' or 'class_', not 'Class' - by convention, capitalized names are for class (in the OO meaning) names.
=> Python is not PHP: 'please enter your class \n' just works
if Class==(int(input"A1"))
I don't know what you expect this line to do, but it sure looks you don't know either... One thing is sure : a string won't be equal to an integer. Never...
file.close('ClassB1')
Have you read the documentation at all ? It's here (well, for a starter at least) : https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
file.close
You want file.close() here. The parens are NOT optional - if you want to call the method at least.
You're doing a long winded way, you could just open the file after the user gives their answer.
import os
print('hello welcome to maths 2000')
yourClass=input('please enter your class '+"\n")
filename = 'Class{}.txt'.format(yourClass)
name=input('please enter your name '+"\n")
if os.path.exists(filename):
f = open(filename, 'a')
file.write(name+"/n")
file.close()
else:
print ("Class not found")
I just set it up so the input determines the filename it tries to open, and if that file exists it opens it and appends their name.
When you execute these
file=open('ClassA1.txt','a')
file=open('ClassB1.txt','a')
file=open('ClassC1.txt','a')
file variable contains "ClassC1.txt", you are re-assigning the object again and again.
so after whatever check if you execute this:
file.close()
last file will be closed.
Instead I would recommend you first take the input of what file is to be opened and then open that file.
file_name = input("Enter file name")
file = open(file_name, 'a')
#do your work
file.close()
fd = open("Student_info.txt", "a+")
class_info = []
print "Hello, welcome to maths 2000"
class_to_be = raw_input("Please enter your class: ")
name = raw_input("Please enter your name: ")
student = name + " " + class_to_be
class_info.append(student)
print class_info
for students in class_info:
fd.write("%s" %(students))
fd.close()
results:
jester112358#ubuntu:~$ python stackhelp.py
Hello, welcome to maths 2000
Please enter your class: Python-class
Please enter your name: Greenie245
['Greenie245 Python-class']
and writes the content of your list to Student_info.txt
I think it's better to have all the information in one file, but obviously you can have a file for every class if you want.
If you want class for every file, consider using:
for students in class_info:
spl = students.split()
if spl[1] == "A1":
A1=open('ClassA1.txt','a')
A1.write("%s" %(students))
A1.write("\n")
A1.close()
elif ... # add anothor classes here