- Input-Output and Files in Python (Python Open, Read and Write to File)
- Watch the VIDEO Tutorials
- Input-Output in Python
- #1) Output Operation
- #2) Reading Input from the keyboard (Input Operation)
- Files in Python
- #1) Open a File
- #2) Reading Data from the File
- #3) Writing Data to File
- #4) Close a File
- #5) Create & Delete a File
- Python. Урок 12. Ввод-вывод данных. Работа с файлами
- Вывод данных в консоль
- Ввод данных с клавиатуры
- Работа с файлами
- Открытие и закрытие файла
- Чтение данных из файла
- Запись данных в файл
- Дополнительные методы для работы с файлами
- P.S.
- Python. Урок 12. Ввод-вывод данных. Работа с файлами : 2 комментария
Input-Output and Files in Python (Python Open, Read and Write to File)
Our previous tutorial explained about Python Functions in simple terms.
This tutorial we will see how to perform input and output operations from keyboard and external sources in simple terms.
In this Python Training Series, so far we have covered almost all the important Python concepts.
Watch the VIDEO Tutorials
Video #1: Input-Output and Files in Python
Video #2: Create & Delete a File in Python
Note: Skip at 11:37 minute in the below video to watch ‘Create & Delete a File’.
Input-Output in Python
Python provides some built-in functions to perform both input and output operations.
#1) Output Operation
In order to print the output, python provides us with a built-in function called print().
#2) Reading Input from the keyboard (Input Operation)
Python provides us with two inbuilt functions to read the input from the keyboard.
raw_input(): This function reads only one line from the standard input and returns it as a String.
Note: This function is decommissioned in Python 3.
value = raw_input(“Please enter the value: ”); print(“Input received from the user is: ”, value)
Please enter the value: Hello Python
Input received from the user is: Hello Python
input(): The input() function first takes the input from the user and then evaluates the expression, which means python automatically identifies whether we entered a string or a number or list.
But in Python 3 the raw_input() function was removed and renamed to input().
value = input(“Please enter the value: ”); print(“Input received from the user is: ”, value)
Please enter the value: [10, 20, 30]
Input received from the user is: [10, 20, 30]
Files in Python
A file is a named location on the disk which is used to store the data permanently.
Here are some of the operations which you can perform on files:
#1) Open a File
Python provides a built-in function called open() to open a file, and this function returns a file object called the handle and it is used to read or modify the file.
file_object = open(filename)
I have a file called test.txt in my disk and I want to open it. This can be achieved by:
#if the file is in the same directory f = open(“test.txt”) #if the file is in a different directory f = open(“C:/users/Python/test.txt”)
We can even specify the mode while opening the file as if we want to read, write or append etc.
If you don’t specify any mode by default, then it will be in reading mode.
#2) Reading Data from the File
In order to read the file, first, we need to open the file in reading mode.
f = open(“test.txt”, ‘r’) #To print the content of the whole file print(f.read()) #To read only one line print(f.readline())
Example: 2
#3) Writing Data to File
In order to write the data into a file, we need to open the file in write mode.
f = open(“test.txt”, ‘w’) f.write(“Hello Python \n”) #in the above code ‘\n’ is next line which means in the text file it will write Hello Python and point the cursor to the next line f.write(“Hello World”)
Now if we open the test.txt file, we can see the content as:
Hello Python
Hello World
#4) Close a File
Every time when we open the file, as a good practice we need to ensure to close the file, In python, we can use close() function to close the file.
When we close the file, it will free up the resources that were tied with the file.
f = open(“test.txt”, ‘r’) print (f.read()) f.close()
#5) Create & Delete a File
In python, we can create a new file using the open method.
Similarly, we can delete a file using the remove function imported from the os.
import os os.remove(“file.txt”)
In order to avoid the occurrence of an error first, we need to check if the file already exists and then remove the file.
import os if os.path.exists(“file.txt”): os.remove(“file.txt”) print(“File deleted successfully”) else: print(“The file does not exist”)
Using python input/output functions, we can get the input from the user during run-time or from external sources like text file etc. Hope you will be clear about Input-Output and Files in Python from this tutorial.
Our upcoming tutorial will explain about the various Types of Oops available in Python!!
Python. Урок 12. Ввод-вывод данных. Работа с файлами
В уроке рассмотрены основные способы ввода и вывода данных в Python с использованием консоли, и работа с файлами: открытие, закрытие, чтение и запись.
Вывод данных в консоль
Один из самых распространенных способов вывести данные в Python – это напечатать их в консоли. Если вы находитесь на этапе изучения языка, такой способ является основным для того, чтобы быстро просмотреть результат свой работы. Для вывода данных в консоль используется функция print.
Рассмотрим основные способы использования данной функции.
>>> print("Hello") Hello >>> print("Hello, " + "world!") Hello, world! >>> print("Age: " + str(23)) Age: 23
По умолчанию, для разделения элементов в функции print используется пробел.
Для замены разделителя необходимо использовать параметр sep функции print.
В качестве конечного элемента выводимой строки, используется символ перевода строки.
>>> for i in range(3): print("i: " + str(i)) i: 0 i: 1 i: 2
Для его замены используется параметр end.
>>> for i in range(3): print("[i: " + str(i) + "]", end=" -- ") [i: 0] -- [i: 1] -- [i: 2] --
Ввод данных с клавиатуры
Для считывания вводимых с клавиатуры данных используется функция input().
Для сохранения данных в переменной используется следующий синтаксис.
>>> a = input() hello >>> print(a) hello
Если считывается с клавиатуры целое число, то строку, получаемую с помощью функции input(), можно передать сразу в функцию int().
>>> val = int(input()) 123 >>> print(val) 123 >>> type(val) class 'int'>
Для вывода строки-приглашения, используйте ее в качестве аргумента функции input().
>>> tv = int(input("input number: ")) input number: 334 >>> print(tv) 334
Преобразование строки в список осуществляется с помощью метода split(), по умолчанию, в качестве разделителя, используется пробел.
>>> l = input().split() 1 2 3 4 5 6 7 >>> print(l) ['1', '2', '3', '4', '5', '6', '7']
Разделитель можно заменить, указав его в качестве аргумента метода split().
>>> nl = input().split("-") 1-2-3-4-5-6-7 >>> print(nl) ['1', '2', '3', '4', '5', '6', '7']
Для считывания списка чисел с одновременным приведением их к типу int можно воспользоваться вот такой конструкцией.
>>> nums = map(int, input().split()) 1 2 3 4 5 6 7 >>> print(list(nums)) [1, 2, 3, 4, 5, 6, 7]
Работа с файлами
Открытие и закрытие файла
Для открытия файла используется функция open(), которая возвращает файловый объект. Наиболее часто используемый вид данной функции выглядит так open(имя_файла, режим_доступа).
Для указания режима доступа используется следующие символы:
‘r’ – открыть файл для чтения;
‘w’ – открыть файл для записи;
‘x’ – открыть файл с целью создания, если файл существует, то вызов функции open завершится с ошибкой;
‘a’ – открыть файл для записи, при этом новые данные будут добавлены в конец файла, без удаления существующих;
‘+’ – открывает файл для обновления.
По умолчанию файл открывается на чтение в текстовом режиме.
У файлового объекта есть следующие атрибуты.
file.closed – возвращает true если файл закрыт и false в противном случае;
file.mode – возвращает режим доступа к файлу, при этом файл должен быть открыт;
>>> f = open("test.txt", "r") >>> print("file.closed: " + str(f.closed)) file.closed: False >>> print("file.mode: " + f.mode) file.mode: r >>> print("file.name: " + f.name) file.name: test.txt
Для закрытия файла используется метод close().
Чтение данных из файла
Чтение данных из файла осуществляется с помощью методов read(размер) и readline().
Метод read(размер) считывает из файла определенное количество символов, переданное в качестве аргумента. Если использовать этот метод без аргументов, то будет считан весь файл.
>>> f = open("test.txt", "r") >>> f.read() '1 2 3 4 5\nWork with file\n' >>> f.close()
В качестве аргумента метода можно передать количество символом, которое нужно считать.
>>> f = open("test.txt", "r") >>> f.read(5) '1 2 3' >>> f.close()
Метод readline() позволяет считать строку из открытого файла.
>>> f = open("test.txt", "r") >>> f.readline() '1 2 3 4 5\n' >>> f.close()
Построчное считывание можно организовать с помощью оператора for.
>>> f = open("test.txt", "r") >>> for line in f: . print(line) . 1 2 3 4 5 Work with file >>> f.close()
Запись данных в файл
Для записи данных файл используется метод write(строка), при успешной записи он вернет количество записанных символов.
>>> f = open("test.txt", "a") >>> f.write("Test string") 11 >>> f.close()
Дополнительные методы для работы с файлами
Метод tell() возвращает текущую позицию “условного курсора” в файле. Например, если вы считали пять символов, то “курсор” будет установлен в позицию 5.
>>> f = open("test.txt", "r") >>> f.read(5) '1 2 3' >>> f.tell() 5 >>> f.close()
Метод seek(позиция) выставляет позицию в файле.
>>> f = open("test.txt", "r") >>> f.tell() 0 >>> f.seek(8) 8 >>> f.read(1) '5' >>> f.tell() 9 >>> f.close()
Хорошей практикой при работе с файлами является применение оператора with. При его использовании нет необходимости закрывать файл, при завершении работы с ним, эта операция будет выполнена автоматически.
>>> with open("test.txt", "r") as f: . for line in f: . print(line) . 1 2 3 4 5 Work with file Test string >>> f.closed True
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
>>
Python. Урок 12. Ввод-вывод данных. Работа с файлами : 2 комментария
- Моксим23.11.2020 “Преобразование строки в список осуществляется с помощью метода split(), по умолчанию, в качестве разделителя, используется пробел.”
Разделитель по умолчанию не пробел, а пустое пространство
- Алексей 01.06.2021 Ого, действительно:
>>> “1 2 3 4 5 7”.split()
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘7’]
И даже так:
>>> “1 2 \n 21 12 4”.split()
[‘1’, ‘2’, ’21’, ’12’, ‘4’]