Text File (Creation/Editing) + Python + Raspberry Pi

From ESE205 Wiki
(Redirected from How to Update A Text File)
Jump to: navigation, search

Purpose

Python is a very useful coding language which has many advantages to other languages depending on what you are doing. However, python does lack in its ability to edit texts files as easily as other languages like java. In many projects that use python you may find a need to edit a text file and not know how to do it.

The purpose of this tutorial is to educate programmers on how to edit text files efficiently and effectively in python. Once this tutorial is complete, programmers should have a basic understanding of how to edit text files.

Creating a Text File for Raspberry Pi

Creating a text file on the Raspberry Pi 3 is pretty simple. You just have to follow a few steps:

1) Open the terminal

2) Go to the directory where you want the text file created using the follow line of code.

cd /pi/directory 

3) Once you are in the directory, just enter the following code where filename is whatever you want the file to be named.

touch filename.txt

Editing a Text File in Python

Python differentiates from java in that you cannot just add lines to a text file or just read it. In python there are four methods:

'r'-This method is for reading text files, but not editing them.

'w'-This method is for writing in text files, but when you enter the writing method, it will delete any file with the same name as your edited file.

'a'-This method is for appending text files. This will add things to the bottom of the text file and nowhere else.

'r+'-This method can both read and write in programs, but sometimes does not work, so it is best to stick to the other three methods.

When using these four methods you must pick which method you think would work best for what you are trying to do. When you want to do something with a text file, you must first assign it as a variable using the following code.

 x = open('file.txt', 'method')

Then if you would like to do anything from that method like read or write in it, you simply call the variable. To write something, you should convert what you are trying to write into a variable.

 y = "Hello World!" 
 x.write(y)

When it writes, it always writes on the bottom line of the text file, so if you want to add something to the middle, you may have to come up with a work around. When you are done editing a text file, be sure to include the line X.close() which closes the text file which will let your computer run faster.