RUVIDEO
Поделитесь видео 🙏

Python File Handling Tutorial | How to read and write files in python ? | File handling in python

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing and reading files.

In this tutorial, we will learn

How to Create a Text File
How to Append Data to a File
How to Read a File
How to Read a File line by line
File Modes in Python
How to Create a Text File
With Python you can create a .text files (guru99.txt) by using the code, we have demonstrated here how you can do this

Step 1)

f= open("guru99.txt","w+")
We declared the variable f to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
Here, we used "w" letter in our argument, which indicates write and will create a file if it does not exist in library
Plus sign indicates both read and write.
The available option beside "w" are, "r" for read, and "a" for append
Step 2)

for i in range(10):
f.write("This is line %d\r\n" % (i+1))
We have a for loop that runs over a range of 10 numbers.
Using the write function to enter data into the file.
The output we want to iterate in the file is "this is line number", which we declare with write function and then percent d (displays integer)
So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character
Step 3)

f.close()
This will close the instance of the file guru99.txt stored
Here is the result after code execution

Python FILE Tutorial: Create, Append, Read, Write

When you click on your text file in our case "guru99.txt" it will look something like this

Python FILE Tutorial: Create, Append, Read, Write

How to Append Data to a File
You can also append a new text to the already existing file or the new file.

Step 1)

f=open("guru99.txt", "a+")
Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.

Step 2)


for i in range(2):
f.write("Appended line %d\r\n" % (i+1))
This will write data into the file in append mode.

Python FILE Tutorial: Create, Append, Read, Write

You can see the output in "guru99.txt" file. The output of the code is that earlier file is appended with new data.

Python FILE Tutorial: Create, Append, Read, Write

How to Read a File
Not only you can create .txt file from Python but you can also call .txt file in a "read mode"(r).

Step 1) Open the file in Read mode

f=open("guru99.txt", "r")
Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead

if f.mode == 'r':
Step 3) Use f.read to read file data and store it in variable content

contents =f.read()
Step 4) print contents

Here is the output


Python FILE Tutorial: Create, Append, Read, Write

How to Read a File line by line
You can also read your .txt file line by line if your data is too big to read. This code will segregate your data in easy to ready mode

Python FILE Tutorial: Create, Append, Read, Write

When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python
Mode Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Python File Handling Tutorial | How to read and write files in python ? | File handling in python», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.