Writing to Files:
- File object is providing write() method to write contents into file.
- We use either write mode or append mode to write the information.
- If we open the file in write mode and the file is not present ; It creates the new file with specified name.
with open("./copy.txt" , "w") as file :
file.write("This is online\n")
file.write("Python session\n")
file.write("Learning Files concept\n")
print("content written")
Output:
Copy the complete file:
class Copy:
src = None
dest = None
def main():
try:
Copy.src = open("./script.py" , "r")
Copy.dest = open("./copy.txt" , "w")
for line in Copy.src:
Copy.dest.write(line)
print("File copied")
except Exception as e:
print("Exception :", e)
finally:
if Copy.dest != None:
Copy.dest.close()
if Copy.src != None:
Copy.src.close()
return
Copy.main()