Files Tutorial (in Python)!!
Files Tutorial (in Python)!!
Introduction
Hello, Replit Community and everyone else looking at this tutorial. This tutorial is mainly working with files (in Python). Good luck, and I hope you learn something about this tutorial!
Why
Files are good to work with. They can store lots of data, and you can read, write, or both from the file! For example, a file can store the scores of a game (
open()
Parameters
The parameters for the open()
function that is needed for the with statement is showed below.
open(filename, mode)
Reading Files
Now, we will demonstrate how to work with with statements. Below, you can find lots of examples to help you with your understanding.
For each of the examples below, also make sure to check out what is in the files. You can find it right below the actual code goes.
Example 1
file.text (You can name a file any name, mostly people use 'txt' type files, for text)
1 2 3 4 5
with open('file.py', 'r') as file: for num in file: num = num[:-1]
Output:
1 2 3 4 5
First, we use a with statement (basically assigning file
to open('file.txt', 'r')
. Then, we use a for loop to break up the file into lines. Strangely, there is a extra character at the end of each line that is not the file text, so we do num = num[:-1]
to solve it (basically cutting off the last index of num
).
Example 2
letter.txt
Dear Grandma, I hope you are having a good time in New York. I heard that your arm is starting to hurt; I hope that you will be just fine. Don't miss us, we will be coming at Christmas! See you then! Sincerely, your grandson, Luke
To print this letter written in the file, we will do something similar to last time. However, we will use another method to open the file.
file = open('letter.txt','r') for line in file: line = line[:-1] print(line)
Output:
Dear Grandma, I hope you are having a good time in New York. I heard that your arm is starting to hurt; I hope that you will be just fine. Don't miss us, we will be coming at Christmas! See you then! Sincerely, your grandson, Luke
We printed the text inside letter.txt
, but with a new strategy. You see, the with statement just assigned variable file
to open('letter.txt', 'r')
.
Writing Files
Writing files can seem a little tricky at first, but should be easier than reading files! Writing files are less commonly used, but it is still useful; maybe you will use it one day!
Example 1
Let's say we have an empty file:
hello_world.txt
The code shown below will be for our main.py
file.
with open('hello_world.txt', 'w') as file: file.write("Hello, world!")
After the code is ran, the file hello_world.txt
will now have some text in it, 'Hello, world!'.
Output:
hello_world.txt
Hello, world!
Note that we need to set the second parameter of open()
to 'w', so that it is in writing mode; if you set it to reading mode, then it would return a error.
Example 2
Let's say you have a list of 10 numbers, and you want to dump all of the numbers into a file to store instead.
numbers.txt
list = [1,6,3,9,12,5,8,5,0,13] with open('numbers.txt', 'w') as file: for num in list: file.write(str(num) + "\n")
First, we create a list that contains 10 numbers. We start by using a with statement to open the file as writing mode, then we use a for loop to get every element from the list in order.
Output:
numbers.txt
1 6 3 9 12 5 8 5 0 13
Reading And Writing Files
Reading and writing files at the same time can be quite confusing. However, it is quite useful! If you copy the code (and the file) in the Writing Files section (any of the examples in that part), you can probably notice that every time you run it, the file should be updated with text, then when you run it again, the file clears, and the cycle goes all over again.
When you write a file, it does that. However, if you read and write a file at the same time, you basically save the contents of the file (to read it), and write it too! The result is that the file will run on its own without clearing, which would be a good idea for saving scores and finding high scores! Good luck with it!
Example 1
We want to make a function that saves a player's score (part 1) and another function that finds the high score (part 2), all using files. Have a thought about it, then look below for the answers!
Part 1
scores.txt
def add_score(score): with open('scores.txt', 'a') as file: file.write(str(score) + "\n")
That is the first function, for the first part. We use a with statement to open the file, then we write in it. Notice that we are in mode 'a'.
add_score(5) add_score(26) add_score(11) add_score(45) add_score(65)
Output:
scores.txt
5 26 11 45 65
Part 2
Now, let's try to get the high score, using the data from the file.
scores.txt
5 26 11 45 65
def get_highscore(): score_list = [] with open('scores.txt', 'r') as file: for score in file: score = score[:-1] score_list.append(score) return max(score_list)
Now, let's test it!
get_highscore()
Output:
65
nice
@ruiwenge2 Sorry, not done yet.
@ruiwenge2 I'm not very used to Markdown yet, so I'm writing, then updating, then writing and so on until I feel like this is finished, thanks!
According to the description, these tutorials are useful to add information and data into python files. The politics dissertation help and offer professional assistance to write quality content.
Thanks for the upvotes!