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
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()
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.
Very newbie programmer, sorry if this is stupid or if my English is wrong. So, I have this command line address book that I am writing. It consists of a dictionary that holds an object with the key as the name variable, and each object has variables associated with it like the name of the person, the email, etc... It works, but now I'm trying to make it store the dictionary persistenly in memory using pickle.
def create_person():
"""Adds an instance object of the Person class to the dictionary persons. persons is a global variable, that has been created previously. DATA is a variable that points to a file named test.data that exists in the same directory as the script."""
name = raw_input("Enter the person's name here: ")
email = raw_input("Enter the person's email here: ")
phone = raw_input("Enter the person's phone here: ")
address = raw_input("Enter the person's address here: ")
f = open(DATA, "rb")
persons = pickle.load(f) #assign whatever is saved in the dictionary in persistent memory to global variable persons, which is empty at this point in the beginning
f.close()
persons[name] = Person(name, email, phone, address)
f = open(DATA, "wb")
pickle.dump(persons, f)
f.close()
However, I'm getting this error:
Traceback (most recent call last):
File "testpickle.py", line 85, in <module>
main()
File "testpickle.py", line 40, in main
create_person()
File "testpickle.py", line 20, in create_person
persons = pickle.load(f)
File "/home/pedro/anaconda/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/home/pedro/anaconda/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/home/pedro/anaconda/lib/python2.7/pickle.py", line 880, in load_eof
raise EOFError
EOFError
I don't understand this. I had actually already written this program, and it was working with memory saving, but I accidently deleted it. What is happening?
pickle hitting EOF is a sure tell the file is corrupt (probably truncated, maybe a write operation failed).
If you upload it somewhere, we might be able to deduce what exactly is wrong with it. In the worst case, you'll have to peek inside and deduce the data that was there to re-input it by hand.
That's your price for using an unreadable format and not paying attention to its integrity (e.g. writing to another file and only moving it over the original one after saving succeeded).
UPDATE:
If you want to start from a new, "empty" file, then handle the case when the file is missing and produce an empty dict. After all, the file is supposed to be missing initially, isn't it?
An empty file is not valid pickle data (it has to at least contain information about the object's type).
Here's "one obvious way" ((c) Python Zen) to handle a missing file:
import errno
try: f = open(DATA, "rb")
except IOError,e:
if e[0]==errno.ENOENT: persons={}
else: raise
else:
persons = pickle.load(f)
f.close()
del f
I don't see anything obviously wrong with your code, but if you just want to store key/value pairs like this, you probably ought to use the shelve module instead of a home-brewed solution.
import shelve
persons = shelve.open(DATA)
def create_person():
"""Adds an instance object of the Person class to the dictionary persons. persons is a global variable, that has been created previously. DATA is a variable that points to a file named test.data that exists in the same directory as the script."""
name = raw_input("Enter the person's name here: ")
email = raw_input("Enter the person's email here: ")
phone = raw_input("Enter the person's phone here: ")
address = raw_input("Enter the person's address here: ")
persons[name] = Person(name, email, phone, address)
while more_people:
create_person()
persons.close()
I am trying to build a function that asks the user to input the name of a file, opens the file, reads its contents, prints the contents of the file on the screen, and closes the file. If no such file exists, it's okay if the script crashes. When I run the function, it gives me: NameError: name 'myInput' is not defined, and I'm not sure how to fix it.
Here is what I have so far:
print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
data = infile.read()
print(data)
Help if you can..
myInput is an undefined variable, and I can't fathom what you had in mind by using it.
Maybe where you show the code...:
print(input('Please enter the name of a file that you want to open.' + myInput))
with open(r"C:\Python32\getty.txt", 'r') as infile:
you actually meant something very different, e.g like...:
myInput = input('Please enter the name of a file that you want to open.')
with open(myInput, 'r') as infile:
...?
In your first line, you have:
print(input('Please enter the name of a file that you want to open.' + myInput))
do you have myInput defined? You need to define it. If you don't have it defined before that line, your script will crash.
This can be gleaned from your helpful error message:
NameError: name 'myInput' is not defined
Which means that the variable myInput is not defined, so the compiler doesn't know what to put there.
I think something like this would solve your problem
fileName = raw_input("Please enter the name of a file that you want to open. ")
fileObject = open(fileName, "r")
fileText = fileObject.read()
print(fileText)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Fixed code;
if os.path.isfile(external_file):
with open(external_file) as in_f:
name = in_f.read()
else:
name = raw_input("What's your name?")
with open(external_file, "w") as out_f:
out_f.write(name)
The problem is.
It refers to every computer that uses it with the name that is stored in .txt.
I need to have a different .txt for every mac address/ip/computer
I also need the name to be changed on command from the user
Also if there is no name in .txt it does not ask for the name?
You may try to do this in such way that first simply ask the user's name, then check if the file names.txt exists or not, if not then create a new file with the name names.txt and append the user's name to it. If the file exists now check if it contains user's name or not, if it contains then say 'Hi+ name', else append the name to the file.
Here is a quick and dirty fix for your code (can be improved further!):
import os
#hard code the path to the external file
external_file = 'names.txt'
#Ask the user's name
name = raw_input("What's your name?")
#if file exists, use it to load name, else create a new file
if not os.path.exists(external_file):
with open(external_file, "a") as f: # using "a" will append to the file
f.write(name)
f.write("\n")
f.close()
else:
#if file exists, use it to load name, else ask user
with open(external_file, "r+") as f:# r+ open a file for reading & writing
lines = f.read().split('\n') # split the names
#print lines
if name in lines:
print "Hi {}".format(name)
else:
f.seek(0,2) # Resolves an issue in Windows
f.write(name)
f.write("\n")
f.close()
Update: Modified version to check for a harcoded name only:
import os
#hard code the path to the external file
external_file = 'names.txt'
username = 'testuser'# Our hardcoded name
#if file doesn' exists, create a new file
if not os.path.exists(external_file):
#Ask the user's name
name = raw_input("What's your name?")
with open(external_file, "a") as f: # using "a" will append to the file
f.write(name)# Write the name to names.txt
f.write("\n")
f.close()
else:
#if file exists, use it to load name, else ask user
with open(external_file, "r+") as f:# r+ open a file for reading & writing
lines = f.read().split('\n') # split the names
print lines
if username in lines: #Check if the file has any username as 'testuser'
print "Hi {}".format(username)
else: # If there is no username as 'testuser' then ask for a name
name = raw_input("What's your name?")
f.seek(0,2) # Resolves an issue in Windows
f.write(name)# Write the name to names.txt
f.write("\n")
f.close()
Reason for using file.seek() is here.