LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Python Data Science File Handling In Python: Creating A File Write/Create Files In Python
How to write/create Python File?
Write to an Existing File: To write to an existing file, you must add a parameter to the open() function.
"a" - Append - will append to the end of the file.
"w" - Write - will overwrite any existing content.
Example 8: Open the file "exampleb.txt" and append content to the file.
Code
f = open("exampleb.txt", "a")
f.write("This is the additional content!")
f.close()
#open and read the file after the appending:
f = open("exampleb.txt", "r")
print(f.read())
Output will be
ILLUSTRATION
This is Line 2.
This is Line 3.
This is Line 4.
This is Line 5.This is the additional content!
Example 9: Open the file "exampleb.txt" and overwrite the content.
Code
f = open("exampleb.txt", "w")
f.write("The file has been overwritten!")
f.close()
#open and read the file after the appending:
f = open("exampleb.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.
the output will be
The file has been overwritten!
Create a New File
How to create a new file?
To create a new file in Python, use the open() method, with one of the following parameters.
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example 10: Create a file called "newexample.txt".
Code
f = open("newexample.txt",
"x")
Result: This will create a new empty file.
To check examine the location where you created it!
Example 11: Create a new file if it does not exist.
f = open("mynewexample.txt",
"w")