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.
Related
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.
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
Okay so I'm trying to write a script that takes two files and modifies the first before writing it into the destination fine, but whenever I run it, the script only prints the first modified line over and over again.
#3a
def modify(string):
"""Takes a string and returns a modified version of the string using two modifications. One must be a replacement of some kind.
string -> string"""
while string != "":
string = string.upper()
string = string.replace("A","4").replace("B","8").replace("C","<").replace("E","3").replace("G","6").replace("I","1").replace("O","0").replace("R","|2").replace("S","5").replace("T","7").replace("Z","2")
print(string)
#3b - asks the user to type in a source code filename and destination filename; opens the files; loops through the contents of the source file line-by-line, using modify() to modify eat line before writing it to the destination file; the closes both files.
source = input("What file would you like to use?")
destination = input("Where would you like it to go?")
filesource = ""
while filesource == "":
try:
file_source = open(source, "r")
file_destination = open(destination, "w")
for item in file_source:
mod = modify(item)
file_destination.write(mod)
file_source.close()
file_destination.close()
break
except IOError:
source = input("I'm sorry, something went wrong. Give me the source file again please?")
Any help?
Hint: if you run modify("TEST ME") what does it return?
add return string to the end of the modify function.
The string never empties - try parsing through it char by char using an index int and your conditional being while i < len(string)
This answer was solved by doing print (file.read())
I have a project called 'PyDOS'. I recently discovered that you can read and write files in Python, I implemented this and the writing bit worked. But when trying the read part, it gives a syntax. The code that's messing up the reading part is:
print file.read
This is the code with the first error:
def textviewer():
print ("Text Viewer.")
file_name = input("Enter a text file to view: ")
file = open(file_name, "r")
print file.read #This returns 'Syntax Error' when pressing F5
input("Press enter to close")
def edit(): #However, the writing function works just fine.
os.system('cls' if os.name == 'nt' else 'clear')
print ("EDIT")
print ("-------------")
print ("Note: Naming this current document the same as a different document will replace the other document with this one.")
filename = input("Plese enter a file name.")
file = open(filename, "w")
print ("Now, Write 5 lines.")
line1 = input()
line2 = input()
line3 = input()
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.close()
print ("File saved!")
time.sleep(3)
It returns syntax error, I tried file.read() but instead showed:
<built-in method read of _io.TextIOWrapper object at 0x10ada08>
<built-in method read of _io.TextIOWrapper object at 0x10ada08>
That's the string representation of a function. What you want isn't the function itself, but rather to call the function.
In other words, you want file.read() instead of file.read.
Also, in Python 3.x, print is a function, not a keyword, so you want print(file.read()), not print file.read().
Incidentally, file is the name of a built-in function (albeit a deprecated one), so you should use a different variable name.
I'm having a little issue with my code, mainly (I think) with the try/except part. My code will generate a wordlist of the users choice. Here is the code:
def gen_wordlist():
filename = input("Please enter the name of the wordlist: ")
try:
my_file = open(filename, 'r')
except FileNotFoundError:
retry = input("No file named "+filename+". Would you like to try again (y/n)")
if retry == 'y' or retry == 'Y':
gen_wordlist()
else:
print("Goodbye :-)")
sys.exit()
words = my_file.read()
my_file.close()
return(words.split())
words = gen_wordlist()
If I enter a valid filename on the first attempt, it works as it should. However, if I enter an invalid filename and choose to try again, I get the following error, even if my second attempt is definitely a valid filename:
Traceback (most recent call last):
File "TEST.py", line 20, in <module>
words = gen_wordlist()
File "TEST.py", line 15, in gen_wordlist
words = my_file.read()
UnboundLocalError: local variable 'my_file' referenced before assignment
I can't work out why though. Surely, when I select 'y', the code just executes from the beginning of the gen_wordlist() function, and should work the same as if I had entered a valid filename on the first attempt, right?
If the open() call raises a FileNotFoundError exception, my_file was never set and all other references trying to use that name will fail.
That includes the code after gen_wordlist() was called in the exception handler. Sure, the new call may succeed, but that call then returns back to this frame where my_file was not set.
You want to return here too, instead:
if retry == 'y' or retry == 'Y':
return gen_wordlist()
Otherwise you'll ignore the result of the successful recursive call here too.
It's not a great idea to use recursion to handle errors in user input. Use a loop instead:
my_file = None
while my_file is None:
filename = input("Please enter the name of the wordlist: ")
try:
my_file = open(filename, 'r')
except FileNotFoundError:
retry = input("No file named " + filename + ". Would you like to try again (y/n)")
if retry.lower() == 'y':
# back to the top of the loop
continue
print("Goodbye :-)")
sys.exit()
This while loop then runs until my_file has successfully been set to a file object.
Re-read the error message, it clearly says you have used the variable my_file before assignment. Now, look at your code, when do you define my_file in the except clause? The try falls out without declaring/assigning to the my_file variable in case of an error. Rest, Martijn's answer points out some more issues.