Writing a text file

By using Python, you can create a text file (test.txt). By using the code, writing to a text file is easy. To open a file for writing, we set the second parameter that is in access mode to "w". To write the data into this test.txt file, we use the write() method of the file handle object. Create a script called  text_write.py and write the following content in it:

text_file = open("test.txt", "w")
text_file.write("Monday Tuesday Wednesday Thursday Friday Saturday ")
text_file.close()

Run the preceding script and you will get the output as follows:

Now, check your current working directory. You'll find a test.txt file that we created. Now, check the contents of the file. You will find that the days that we have written in the write() function will be saved in test.txt.

In the preceding program, we've declared the text_file variable to open a file named test.txt. The open function takes two arguments: first, the file that we want to open, and second, the access mode that represents the permission or operation that we want to do or apply on the file. In our program, we used the "w" letter in our second argument, which indicates write. Then, we used text_file.close() to close the instance of the stored test.txt file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset