In this example of Python working with files, we’ll look at the built-in Python tools for working with files: opening / closing, reading, and writing. Until now, we only worked with objects stored in the computer’s RAM. That is, after the completion of the program, all our actions were deleted. Using our sample, you will learn how to work with files in Python, that is, to save the state of the program in a file on the hard disk.
Before you start working on your assignment, you should read through our sample. You can use our sample on Python write to file, as well as for doing any other tasks easily. If you don’t know how to complete your assignment, visit our blog to find the sample that you need. We have examples for tasks of different disciplines. Once you read, for example, the following sample, you will have a clearer understanding on how to do your own task in Python.
Working With Files in Python
Today, examples of how to write to a file and read from it will be discussed.
First, let’s begin with reading from a file. I have created the file ‘prime.txt’ where I have put the following text:
The following code fragment reads data from file and outputs it in console:
In print() function you see another method: rstrip() with the parameter of new line. This is here for deleting additional empty lines that appear if outputting data from file without it.
Another example is related for both reading and writing information. There is another file called ‘details.txt’ that contains several names with surnames.
The purpose of this program is to convert read data from file to dictionary and then in the same way write this data to a new file. The problem here is that data read from the file is of the string type, and it is necessary to split it into smaller pieces in order to be able to operate with them. The same problem occurs when writing data in dictionary to the file: you cannot write it directly; you should convert it to string first. These operations were successfully performed within the following code: