How To Fix File Handling Issues In Python 3
Solution 1:
Hehe, its rather simple... whenever you open a file in a write format, you can only write to it, so to read it you need to close it and then reopen it as a read format.
example:
file=open("Example.txt","w")
file.write("Some text")
file.close()
file=open("Example.txt","r")
text=file.read()
print(text)
file.close()
Solution 2:
@Viswamedha Nalabotu Not necessary. you can read and write both. Yeah but using close is better as it can cause some problems. Thats why the with method was introduced. But as i mentioned before, there was a minor bug in VSC and a i got it how to do that.
you can read and write this way:
f=open("note.txt",'w+')
f.write("is it working still ?")
f.seek(0)
content=f.read()
print (content)
Solution 3:
import sys
import os
import shutil
defleave():
sys.exit("You are leaving CUI Text Editor")
defread():
try:
filename = input("Enter file name: ")
target = open(filename, "r")
readfile = target.read()
print(readfile)
except Exception as e:
print("There was a problem: %s" % (e))
defdelete():
filename = input("Enter file name: ")
try:
os.unlink(filename)
except Exception as e:
print("There was a problem: %s" % (e))
defwrite():
try:
filename = input("Enter file name: ")
target = open(filename, "a")
whileTrue:
append = input()
target.write(append)
target.write("\n")
if append.lower() == "menu":
breakexcept Exception as e:
print("There was a problem: %s" % (e))
defcwd():
try:
print(os.getcwd())
change = input("Change Y/N: ")
if change.startswith("y"):
path = input("New CWD: ")
os.chdir(path)
except Exception as e:
print("There was a problem: %s" % (e))
defrename():
try:
filename = input("Enter current file name: ")
new = input("Enter new file name: ")
shutil.move(filename, new)
except Exception as e:
print("There was a problem: %s" % (e))
whileTrue:
print("Options: write, read, cwd, exit, delete, rename")
do = input("So, what are you wishing for today: ")
if do.lower() == "write":
write()
elif do.lower() == "read":
read()
elif do.lower() == "delete":
delete()
elif do.lower() == "exit":
leave()
elif do.lower() == "cwd":
cwd()
elif do.lower() == "rename":
rename()
Have my advice, use r+ mode for safety, and use as many try catch blocks you wish to have. file management in python is easy then c++ streams.
Solution 4:
file=open('word.txt','rw+')
file.write("Python you are making me mad")
file.read()
Solution 5:
Okay, after searching and trying finally i got it. First of all it was a bug in Visual Studio code. You need to use exit() in terminal whenever such case occurs. Second you need to use seek(0) before printing, this way the simple program as i shared will run fine.
Post a Comment for "How To Fix File Handling Issues In Python 3"