Handling Txt Files

Storing Data in .txt File

These snippets of code can be used to write/output information from your code to a text file. These text files can then be viewed in something similar to notepad. The code is provided in the context of writing some results for a quiz to a text file along with their name. The import thing when working with files is remember to open the file at the start and close once finished.

The quiz needed to make the code work, you could always code your own!

Writing To a .txt File

The code shown here takes the 2 piece of data and puts them into a list called "data" before writing the info into text file.

Modes

"a" - Append - Add to existing file

"w" - Write - Replace existing file with new data


Inside The Notepad File

Reading From a .txt File

One of the main reasons you export data to from python is so that it can be used at a later date, for example if a teacher was running a quiz and storing the results for each student they may want to analyse the data in some way. The most basic way to do this would be sorting the data into an order.

Reading The Entire File

This code snippets takes the entire text file and outputs in Python. Create a variable to store the command for opening the file then tell Python to read the file.


Reading Specific Lines

This code snippets takes the reads the file in Python and uses the inbuilt readlines() command to treat line as a separate entity.

data=lines[0] is the line of code that picks which line of the file to read, you can read individual lines or a selection of lines as shown in the #comments.


Basic Sorting of The Data

This code snippets takes the reads the file in Python and uses the inbuilt readlines() command to treat line as a separate entity.

It can then sorts the data either numerically or alphabetically depending on the data type.