DEV Community

loading...

write to file python

maxwizardth profile image oladejo abdullahi ・5 min read

How to write in to a file using python.

To write to an existing file, you must add any of the parameter below to the open() function.
"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content
so both 'a' and 'w' work the same way only that 'w' will overwrite the whole page. let's take a look at some examples.

Example

let's say I have a text file name 'myself.txt' with the following content.

myself.txt
This is Oladejo Abdullahi.
he loves writing codes.
his best language is python.
Enter fullscreen mode Exit fullscreen mode

Now let's us open the file and write more content in to it. so we write the following code in test.py

test.py
# we wll open the file "myself.txt" and append content to the file:
myselfFile = open("myself.txt", "a") #this open the file for writing additional content
myselfFile.write("his nickname is Maxwizard!")#this write to the file
myselfFile.close()#the file closed
Enter fullscreen mode Exit fullscreen mode

with the above code we have add more content to myself.txt, you can open the file (myself.txt) to check the content inside and you will see there is additional sentence. And if we like we can read the file and print it out to see the content with the following codes:

# to open and read the file after the appending:
myselfFile = open("myself.txt", "r") # this is in reading mode
print(myselfFIle.read())
Enter fullscreen mode Exit fullscreen mode
Result
This is Oladejo Abdullahi.
he loves writing codes.
his best language is python.
his nickname is Maxwizard
Enter fullscreen mode Exit fullscreen mode

Yeah the result above shows that more content had been written into the file. Now let's try to write in to the file using 'w' mode
using the same file ('myself.txt'). But remember that the file contain four line now so let's try the following code.

Example

# to open the file "myself.txt" and overwrite the content:

file = open("myself.txt", "w")
file.write("hell my bad! I have deleted the content! because I used 'w'")
file.close()
Enter fullscreen mode Exit fullscreen mode

you can now open the file again and see that the content has totally changed. if you don't want to then use the following codes to open file and print to know the content of the file.

#open and read the file after the overwriting:
file = open("myself.txt", "r") # set to read mode to read the file
print(file.read()) #print out all the content
Enter fullscreen mode Exit fullscreen mode
Result
hell my bad! I have deleted the content! because I used 'w'
Enter fullscreen mode Exit fullscreen mode

Did you see the result ? yeah the whole contents has been changed. so avoid using 'w' if you don't want to delete the content in your file.
Notice we are dealing with existing text file in our codes, what if we don't want have the file mentioned or is not found in the directory what is going to happen? can we even create a new file with code? Yeah, keep reading.

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. Now let's write a code to create a newFile.txt. just copy the same code below:

Example

#Create a file called "newFile.txt":

myNewFile= open("newFile.txt", "x")
Enter fullscreen mode Exit fullscreen mode

run the code above and search 'newFile.txt' in your directory and you will see that the file (newFile.txt). Although it is just empty file.
did you seee it?
Now let's run the code again what is the result? Umh? Yeah! it raised error but why? it is because the file has been created before so if you try to create it again it will raise error.

Example

#reate a new file if it does not exist using 'w':
newFile2 = open("newFile2.txt", "w")
Enter fullscreen mode Exit fullscreen mode

the code above will create newFile2.txt and we can write in it if will wish to do so. run the code many times it will not raise any error even though the file has been created in the first runnning.

How to delete file

To delete a file, you must import the OS module, and run its os.remove() function: let's see how it goes with the

Example

# Remove the file "newFile.txt":
import os
os.remove("newFile.txt") 
Enter fullscreen mode Exit fullscreen mode

the code above will deleted the file named 'newFile.txt' but what if the file doesn't even exist what did you think would happpened? Umh? yeah it will raise error! Now that we have know that if the file doesn't exist we get error so how can we control that ? well we can decide to check if the file exist first.
How to check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete it using the if statement with os.path.exist() like the following example.

Example

#Check if file exists, then delete it:

import os
if os.path.exists("newfile3.txt"): # check if the newfile3.txt exist in the directory
  os.remove("newfile3.txt") #delete it if found
else: #if it doesn't exist 
  print("The file does not exist")
Enter fullscreen mode Exit fullscreen mode

this code above will delete the file if it exist and won't raise error it doesn't exist, it would rather print the file does not exist.
So what if we want to delete many files? I mean a folder it self well, it is just a simple logic to do that just keep on reading.

How to delete Folder

To delete an entire folder, just use the os.rmdir() method like the followng

Example

#Remove the folder "myfolder":

import os
os.rmdir("yourFolderName") # change 'yourFolderName' to name of a folder that exist on your computer
Enter fullscreen mode Exit fullscreen mode

don't use the folder that contain important file to text the above codes. But what if the folder specified doesn't exist what would happen? Yeah, it will raise error too. so, to avoid that we can use if like the following.

import os
#Check if file exists, then delete it:
if os.path.exists("New Folder"): # check if the newfile3.txt exist in the directory
  os.rmdir("New Folder") #delete it if found
else: #if it doesn't exist 
  print("The file does not exist")
Enter fullscreen mode Exit fullscreen mode

the code above will not raise error even if the folder name specified is not found. I hope you found this article helpful, consider to follow me and comment below if you have any question or correction. see you in the next lesson where we will be dealing with how to write into csv.

Discussion (0)

Forem Open with the Forem app