Python: write to file - simply explained
On this page we show you how to create and read files with Python ("write to file"). We explain Python so easily and understandably that even beginners can get started quickly.
"write to file" with Python: first open the file
Before reading or editing files with Python ("write to file"), you must first open or create them.
- You can open a file, such as a text file, with the command "file = open (" test.txt ", " w ")" (without quotation marks at the beginning and end). In this case a file called "test.txt" is opened. If this should not yet exist, it would be created automatically.
- The "w" stands for the mode. This stands for the "Write" mode. This mode is used to write and edit new information in a file. However, please note that all existing files with the same name will be deleted.
- Instead, you can also use the read mode with "r". Here, only data can be read from a file and cannot be changed.
- The "Appending" mode, which you can use with "a", is also very practical. With this mode you can only add data at the end of a file. Existing data will not be deleted.
- Finally, there is the "r +" mode, which is a mixture of the read mode and the write mode.
Python: write to file - so use the command
First, we will show you how to write to a file. It is important that you have already opened the file (as described above) with a command.
- Then you can use the command "file.write (" Test \ n ")" to write the word "Test" in your file (without quotation marks). With the "\ n" the cursor is then lowered one line.
- Tip: If you want to add an empty line as a "spacer", you can do this easily with "file.write (" \ n ")".
- Don't forget to close your file at the end with the command "file.close ()".
Read file in Python
Next we show how you can also read data from your file. As already mentioned in the first paragraph, it is sufficient that you only start the file in read mode: "file = open (" test.txt ", " r ")"
- The command to read a file is "file.read ()". You can combine this with a print command, for example: "print (file.read ())"
- With the command "file.read (4)", however, only the first 4 characters are read.
- The "file.readline (3)" command, which only reads the third line, is also very practical.
- Finally, you can use the "print (file.readlines ())" command to read all lines and have them output individually.
More tips about Python in our CHIP guides
Tip: You can find further programming tutorials on our Python programming language topic page. There we will show you, for example, how you can access an HTML website with Python.