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)
Related
I want my code to save information..
for example in here we take a input of what is my name :
your_name = str(input("What is your name : "))
then if i stop the code and run it again i want it to still know my name
but the problem is that when you stop the code everything gets deleted and the program doesn't know what is your name since you stopped the code..
That's how programs work. If you want to persist anything, you can store the information to file and load the information from file the every time the program runs.
For example,
import os
filepath = 'saved_data.txt'
try:
# try loading from file
with open(filepath, 'r') as f:
your_name = f.read()
except FileNotFoundError:
# if failed, ask user
your_name = str(input("What is your name : "))
# store result
with open(filepath, 'w') as f:
f.write(your_name)
With more complex data, you will want to use the pickle package.
import os
import pickle
filepath = 'saved_data.pkl'
try:
# try loading from file
with open(filepath, 'r') as f:
your_name = pickle.load(f)
except FileNotFoundError:
# if failed, ask user
your_name = str(input("What is your name : "))
# store result
with open(filepath, 'w') as f:
pickle.dump(your_name)
To be able to dump and load all the data from your session, you can use the dill package:
import dill
# load all the variables from last session
dill.load_session('data.pkl')
# ... do stuff
# dump the current session to file to be used next time.
dill.dump_session('data.pkl')
I've just had a look around and found the sqlitedict package that seems to make this sort of thing easy.
from sqlitedict import SqliteDict
def main() -> None:
prefs = SqliteDict("prefs.sqlite")
# try getting the user's name
if name := prefs.get("name"):
# got a name, see if they want to change it
if newname := input(f"Enter your name [{name}]: ").strip():
name = newname
else:
# keep going until we get something
while not (name := input("Enter your name: ").strip()):
pass
print(name)
# save it for next time
prefs["name"] = name
prefs.commit()
if __name__ == "__main__":
main()
Note that I'm using Python 3.8's new "Walrus operator", :=, to make the code more concise.
You'll need to rely on a database (like SQLite3, MySQL, etc) if you want to save the state of your program.
You could also writing to the same file you're running and append a variable to the top of the file as well--but that would cause security concerns if this were a real program since this is equivalent to eval():
saved_name = None
if not saved_name:
saved_name = str(input("What is your name : "))
with open("test.py", "r") as this_file:
lines = this_file.readlines()
lines[0] = f'saved_name = "{saved_name}"\n'
with open("test.py", "w") as updated_file:
for line in lines:
updated_file.write(line)
print(f"Hello {saved_name}")
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()
So I basically need to check whether the user's name exists in the .txt file. If it does, it needs to print the line that contains the name. If it doesn't, it needs to add the name.
So I've gotten as far as to copy the name to the .txt file, but it will also write the name if it exists already. Which it's not supposed to do.
This is the current code I have:
f = open("list_users.txt", "a+")
name = input('Enter your username: ')
if name in f:
print('true')
else:
f.write(name)
f.write('\n')
f.close()
I know it's pretty basic, but I can't seem to get any further than this. I have no idea how to get the information out of the file, I can't even check if it exists already.
this code doesn't read the file it is just opening it
name = input('Enter your username: ')
with open('list_users.txt', 'a+') as f:
users = f.read()
if name in users:
print('true')
else:
f.write(naam)
f.write('\n')
Following line is the issue.
if name in f:
Here you are checking if the name is in `file object' instead of checking it in lines.
Change the code like this.
name = input('Enter your username: ')
with open("list_users.txt", "r+") as f:
for line in f.readlines():
if name in line:
print('true')
break
f.write(name + '\n')
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