Im working on a saving system for user names right now. The current variable looks like this: name = input("What is your name"). I have it writing out to a text file.
I tried setting name as a variable without the input, and tried making the input the write function (idk why). No luck with either of those.
def welcome():
os.system('cls' if os.name == "nt" else 'clear')
print(color.color.DarkGray + "Welcome...")
sleep(5)
name = input("Enter Name Here: ")
name1 = name
saveUserInp = open("userNames.txt", 'w')
with open ("userNames.txt") as f:
f.write(name)
sleep(5)
print("Welcome",name1)
sleep(5)
menu()
Provided above is the code for the welcome function.
Traceback (most recent call last):
File "main.py", line 54, in <module>
welcome()
File "main.py", line 21, in welcome
f.write(name)
io.UnsupportedOperation: not writable
Provided is the actual error given. Line 54 is calling the welcome function, which breaks after I type in my name. Like 21 is the f.write function. I am not sure why it doesn't want to write it into the file.
You should open the file specifying the open mode if it's different than read:
with open ("userNames.txt", "w") as f:
f.write(name)
open with no mode provided opens the file in read mode by default, no surprise it's not writable.
By the way, what's the point of opening the file twice? Lines
saveUserInp = open("userNames.txt", 'w')
...
saveUserInp.close()
might be removed since you open file with the with statement.
Related
Foundation year programming student here. I'm trying to do some batch mode processing, Taking a list of names in a file, opening said file, reading it, assigning a username each name in the file and then storing said names in another file.
Here is my code:
# A program which takes a list of names from a file, creates a new file
# and makes a username based on each name into it.
#first open each file
import string
def main():
infileName = raw_input("What file are the names in")
outfileName = raw_input("What file are the usernames going in?")
#open the files
infile = open(infileName, "r")
outfile = open(outfileName, "w")
data = infile.read()
print data
main()
#process each line in the file
for line in infile:
#get the first and last names from line
first, last = string.split(line)
#create a username
uname = string.lower(first[0]+last[:7])
#write it to output file
outfile.write(uname+"\n")
#close both files
infile.close()
outfile.close()
print "The usernames have been written to, ", outfileName
It all seems fine except it comes out with the error code:
Traceback (most recent call last):
File "C:/Users/Manol/OneDrive/Documents/Uni/Programming/File Processing File/BatchUsernames.py", line 23, in <module>
for line in infile:
NameError: name 'infile' is not defined
>>>
I don't understand as I thought I had defined it on line 13
infile = open(infileName, "r")
If anyone could point out what I'm doing wrong it would be much appreciated.
Thanks for you time
Manos
You defined it in your main() function, so it is a local variable. Any function outside of main() won't recognize it. You should probably also use data instead but again, that is a local variable. A possible solution could be something like this:
import string
def main():
infileName = raw_input("What file are the names in")
outfileName = raw_input("What file are the usernames going in?")
#open the files
infile = open(infileName, "r")
outfile = open(outfileName, "w")
data = infile.read()
for line in data:
first, last = string.split(line)
uname = string.lower(first[0]+last[:7])
outfile.write(uname+"\n")
infile.close()
outfile.close()
print(data)
print("The usernames have been written to, ", outfileName)
main()
i am getting some errors that i cant figure out how to fix with the below program, here is the instructions for it.
"Write a program that prompts for two file names and exchanges the contents of the two files. Your program should be sufficiently robust that if a file doesn't exist, the program will re-prompt."
below is the error i get when i am trying to run it. I also evidently still need to make it re-prompt for the user if the files cant is found. I tried a few things to get it to work but was unable to get it to work properly for that as well.
Traceback (most recent call last):
File "C:\Users\istal\Desktop\6.2.py", line 30, in <module>
dataobject.transfer(firstfilename,secondfilename)
File "C:\Users\istal\Desktop\6.2.py", line 5, in transfer
with open(firstfilename,'r')as filedata:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/istal/Desktop/python/testone.tx'
here is the code itself
class DataTransferinFiles():
def transfer(self,firstfilename,secondfilename):
print("your first file is=",firstfilename);
print("your second file is =", secondfilename)
with open(firstfilename,'r')as filedata:
firstfiledata= filedata.readlines()
print()
print("1st file reading complete")
print()
with open(secondfilename, 'r')as filedata:
secondfiledata=filedata.readlines()
print("2st file reading complete")
for eachline in firstfiledata:
filesecond = open(secondfilename,'a')
filesecond.write("/n"+eachline+ "/n")
print ("1st file transfered in to second file")
for eachline in secondfiledata:
filefirst = open(firstfilename)
filefirst.write("\n"+eachline+ "\n")
print ("second file transfered in to first file")
dataobject = DataTransferinFiles()
firstfilename = input("enter first file name for transfer")
secondfilename = input("enter second file name for transfer")
dataobject.transfer(firstfilename,secondfilename)
It's an typo, of the indentation.
The line:
dataobject = DataTransferinFiles()
Should be just:
dataobject = DataTransferinFiles()
So the full code:
class DataTransferinFiles():
def transfer(self,firstfilename,secondfilename):
print("your first file is=",firstfilename);
print("your second file is =", secondfilename)
with open(firstfilename,'r')as filedata:
firstfiledata= filedata.readlines()
print()
print("1st file reading complete")
print()
with open(secondfilename, 'r')as filedata:
secondfiledata=filedata.readlines()
print("2st file reading complete")
for eachline in firstfiledata:
filesecond = open(secondfilename,'a')
filesecond.write("/n"+eachline+ "/n")
print ("1st file transfered in to second file")
for eachline in secondfiledata:
filefirst = open(firstfilename)
filefirst.write("\n"+eachline+ "\n")
print ("second file transfered in to first file")
dataobject = DataTransferinFiles()
firstfilename = input("enter first file name for transfer")
secondfilename = input("enter second file name for transfer")
dataobject.transfer(firstfilename,secondfilename)
I'm seeing a couple of issues.
In the for eachline in... blocks you are trying to reopen files that you have not closed. Add a with when you open them to write, the same way that you used the with context manager for the first. Otherwise you're trying to open the file every time you write a line.
The for eachline in secondfiledata does not append like the first does -- so if you were successfully closing the file, you'd just keep overwriting until the final line.
You're overcomplicating this by using readlines() instad of read().
This assumes that you are reading and writing text in the files. What if it's a binary file?
I recommend perusing https://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files
I have a predefined function that I am currently running to check if a file a input is correct. I wish to open this file in my function with the with" operator. This is what I currently have:
def open_file():
'''Checks if the file is correct.'''
grab_file = True #Creates initial variable that checks if file is correct
while grab_file == True: #Loop initiates the check if true
txt = input("Enter a file name: ") #Asks for file input
try:
f = open(txt) #Tries to open the file
return f #File returned as output
grab_file = False #Stops the loop
except: #File is invalid, prompts for retry
print("Error. Please try again.")
def main():
'''Main function that runs through file and does delta calculations.'''
with open(open_file()) as f:
f.readline()
print_headers()
pass
Not sure what exactly is the issue, thanks! Note the second portion of the code is in its own main function and is not part of the open_file function.
The code gives me an error when I try to run the following:
f.readline()
date = f.readline()
print_headers()
This is the error I am getting, the code after the with open statement are just a simple readline(
"TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper"
Your error is a fairly easy fix:
just replace the
with open(open_file()) as f:
with
with open_file() as f:
because you've already opened the file and returned the open file in the open_file() function.
However the print_headers() function doesn't exist in standard python 3.x so I'm not quite sure if this is your own function or a different mistake.
I am trying to build a program that reads a value from a separate text file. In this case, it is named "Test.lang". It contains the text "Hello World".
My program was working just fine with:
from sys import *
def open_file(filename):
print (filename)
def run():
data = open_file(argv[1])
run()
Then, when I tried to change it to:
from sys import *
def open_file(filename):
data = open(filename, "r").read()
print (data)
def run():
data = open_file(argv[1])
run()
It does not work. I get 4 errors:
Traceback (most recent call last):
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 10, in <module>
run()
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 8, in run
data = open_file(argv[1])
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 4, in open_file
data = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'test.lang'
What is really confusing me is the last one. How did the previous program work, but now test.lang doesn't exist?
Please help me.
Here is how you do this.
To read a file:
file = open('Directory Of The File.txt', 'r')
MyVariable = file.read()
file.close()
To write a file:
file = open('Directory Of The File.txt', 'w')
file.write('Insert Text, Variable or Other Data Here!')
file.close()
It's as easy as that!
You can change the .txt for .lang or any other supported file extension!
Please reply and let me know if this worked for you :)
I'm trying to create a very simple function that will let me edit a file that I've already written using Python 3.5. My writing function works just fine, but I'm including it just in case it matters. It looks like this:
def typer():
print("")
print("Start typing to begin.")
typercommand = input(" ")
saveAs = input("Save file as: ")
with open(saveAs, 'w') as f:
f.write(typercommand)
if saveAs == (""):
commandLine()
commandLine()
My editing function looks like this:
def edit():
file = input("Which file do you want to edit? ")
with open(file, 'a') as f:
for line in f:
print(line)
I then call the function using my command line function like this:
def commandLine():
command = input("~$: ")
if command == ("edit"):
edit()
I don't get any errors but nothing else happens, either (I'm just redirected to my base command line). And by that I mean that I call the function and then, on the line directly beneath it, it get the prompt for the command line I made for the program (~$). What is wrong with my code and what could I do to remedy it?
If you want to read from and write to a file you have to open it with mode 'r+', 'w+' or 'a+'.
Note that 'w+' truncates the file, so you will probably need 'r+' or 'a+', see the doc
Something like:
def edit():
file = input("Which file do you want to edit? ")
with open(file, 'r+') as f:
for line in f:
print(line)
# here you can write to file
...
EDITED: indentation error
In your edit function, you are just printingat the standard output every line, but you are not writing anything.
def edit():
file = input("Which file do you want to edit? ")
with open(file, 'w+') as f:
filetext = ""
for line in f:
filetext += line
# do stuff with filetext
...
# then write the file
f.write(filetext)