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.
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()
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')
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
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.