Home Blog Archive Internet Python: write to file - explained simply

Python: write to file - explained simply

  • Sep 05, 2025
  • 376
  • 0

How you can create Python files and retrieval ("write to file"), we will show you on this page. We explain you with Python so easy and understandable that even beginners can get started quickly.

"write to file" in Python: the first file open

Before reading the files with Python, or edit ("write to file"), you must open the or create.
  • A file, such as, for example, a Text file, you can open with the command "file = open("test.txt","w")" (without the quotation marks at the beginning and the end). In this case, opens a file named "test.txt". If this should not yet exist, would this be automatically created.
  • The "w" stands for the mode. This is the "Write"mode. This mode is used to Write and edit new information in a file. Note, however, that all existing files are deleted with the same name.
  • Instead, you can use "r" to the read mode. In this case, only the data from a file can be read and not changed.
  • Also very handy is the "Appending"mode, you can use the "a" is. 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: open file

Python: write to file - so you can use the command

First of all, we show you how in a file can write. What is important is that you have opened the file (as described above) with a command already.
  • Then you can use the command "file.write("Test\n")" the word "Test" in your file to write (without the quotation marks). The "\n" will set the Cursor, then a row down.
  • Tip: If you want to add as a "spacer", a blank line, this is quite easy with the "file.write("\n")".
  • Do not forget your file at the end with the command "file.to close close()" again.
Python: write to file - how to

File reading in Python

Next, we show how data from your file reading. As in the first paragraph already mentioned, it is sufficient that you start the file in read-only mode: "file = open("test.txt","r")"
  • The command to a file is to read "file.read()". These you can combine, for example, with a print command: "print (file.read())"
  • With the command "file.read(4)" however, read only the first 4 characters.
  • Very convenient, the command "file is also.readline(3)", with the only the third line would read.
  • Finally, you can use the command "print (file.readlines())" all the rows to be read and individually, to output.
File reading in Python

More tips to Python in our CHIP counselors

Tip: On our topic page for the Python programming language, you can find more Tutorials about programming. There we will show you for example how to make a HTML webpage with Python to call can.

YOU MAY ALSO LIKE

0 COMMENTS

LEAVE A COMMENT

Human?
1 + 3 =