Python Write To File-Python Write To Text File:
Python Write To File-Python Write To Text File:
if you are writing to text files in python you will lose all your data in that text file. If anything was there in the text file it's not there anymore. its basically opened the file clear everything and write new data. in the below steps, I will show you how to write a file in python with an example.
Example-1:
x=open('devops.txt','w') x.write('Decoding Devops') x.close()
Output:
devops.txt
Decoding Devops
Open Function:
open is the function in python to open any file. Here we are opening the text file and we are writing into that text file.
If the text file has not existed already it will create that new text file.
The open function requires two arguments one is the path to the filename and write-mode argument. for write mode argument we use "w"
Write Function:
After the opening of the file we have to write into that file for that we use write function.
In the write function, we should use double quotes or single quotes for any text.
Close Function:
after writing into the file. we should close the file. this is the basic syntax in python.
Example-2:
x=open('devops.txt','w') x.write('Decoding Devops') x.write('Decoding Devops') x.write('Decoding Devops') x.close()
Output:
devops.txt
Decoding DevopsDecoding DevopsDecoding Devops
here if the file devops.txt file has not existed then it will create the file and it writes into that file. If the file is already there it will remove all the old data in that file and it writes new data whatever we mentioned in the python file. In the devops.txt file, you can see that we have three times "Decoding DevOps" since we have written three times after opening of the devops.txt file. that is why we got the output file as above.
- writing to file in python 3
- python write to text file
- python write to file
- python append to file
- Writing to a file
- python write to text file
- python write to text file example