- Как прочитать текстовый файл в Python
- Как открыть текстовый файл в Python с помощью open()
- Имена файлов и правильные пути
- Необязательный параметр режима в open()
- Дополнительные параметры для функции open() в Python
- Метод readable(): проверка доступности файла для чтения
- Что такое метод read() в Python?
- Что такое метод close() в Python?
- Как использовать ключевое слово with в Python
- Что такое метод readline() в Python?
- Что такое метод readlines() в Python?
- Как прочитать текстовый файл при помощи цикла for
- Заключение
- Python Open File – How to Read a Text File Line by Line
- What is the open() function in Python?
- File names and correct paths
- Optional Mode parameter in open()
- Additional parameters for the open() function in Python
- What is the readable() method in Python?
- What is the read() method in Python?
- What is the close() method in Python?
- How to use the with keyword to close files in Python
- What is the readline() method in Python?
- What is the readlines() method in Python?
- How to use a for loop to read lines from a file in Python
- Conclusion
Как прочитать текстовый файл в Python
В Python есть несколько способов прочитать текстовый файл. В этой статье мы рассмотрим функцию open() , методы read() , readline() , readlines() , close() и ключевое слово with .
Как открыть текстовый файл в Python с помощью open()
Если вы хотите прочитать текстовый файл с помощью Python, вам сначала нужно его открыть.
Вот так выглядит основной синтаксис функции open() :
open("name of file you want opened", "optional mode")
Имена файлов и правильные пути
Если текстовый файл, который нужно открыть, и ваш текущий файл находятся в одной директории (папке), можно просто указать имя файла внутри функции open() . Например:
На скрине видно, как выглядят файлы, находящиеся в одном каталоге:
Но если ваш текстовый файл находится в другом каталоге, вам необходимо указать путь к нему.
В этом примере файл со случайным текстом находится в папке, отличной от той, где находится файл с кодом main.py:
В таком случае, чтобы получить доступ к этому файлу в main.py, вы должны включить имя папки с именем файла.
Если путь к файлу будет указан неправильно, вы получите сообщение об ошибке FileNotFoundError .
Таким образом, чтобы указать путь к файлу правильно, важно отслеживать, в каком каталоге вы находитесь.
Необязательный параметр режима в open()
При работе с файлами существуют разные режимы. Режим по умолчанию – это режим чтения.
Вы также можете опустить mode= и просто написать «r» .
Существуют и другие типы режимов, такие как «w» для записи или «a» для добавления. Мы не будем вдаваться в подробности о других режимах, потому что в этой статье сосредоточимся исключительно на чтении файлов.
Полный список других режимов можно найти в документации.
Дополнительные параметры для функции open() в Python
Функция open() может также принимать следующие необязательные параметры:
Если вы хотите узнать больше об этих опциональных параметрах, можно заглянуть в документацию.
Метод readable(): проверка доступности файла для чтения
Если вы хотите проверить, можно ли прочитать файл, используйте метод readable() . Он возвращает True или False .
Следующий пример вернет True , потому что мы находимся в режиме чтения:
file = open("demo.txt") print(file.readable())
Если бы мы изменили этот пример на режим «w» (для записи), тогда метод readable() вернул бы False :
file = open("demo.txt", "w") print(file.readable())
Что такое метод read() в Python?
Метод read() будет считывать все содержимое файла как одну строку. Это хороший метод, если в вашем текстовом файле мало содержимого .
В этом примере давайте используем метод read() для вывода на экран списка имен из файла demo.txt:
file = open("demo.txt") print(file.read())
Запустим этот код и получим следующий вывод:
# Output: # This is a list of names: # Jessica # James # Nick # Sara
Этот метод может принимать необязательный параметр, называемый размером. Вместо чтения всего файла будет прочитана только его часть.
Если мы изменим предыдущий пример, мы сможем вывести только первое слово, добавив число 4 в качестве аргумента для read() .
file = open("demo.txt") print(file.read(4)) # Output: # This
Если аргумент размера опущен или число отрицательное, то будет прочитан весь файл.
Что такое метод close() в Python?
Когда вы закончили читать файл, необходимо его закрыть. Если вы забудете это сделать, это может вызвать проблемы и дальнейшие ошибки.
Вот пример того, как закрыть файл demo.txt:
file = open("demo.txt") print(file.read()) file.close()
Как использовать ключевое слово with в Python
Один из способов убедиться, что ваш файл закрыт, – использовать ключевое слово with . Это считается хорошей практикой, потому что файл закрывается не вручную, а автоматически. Более того, это просто крайне удобно и защищает вас от ошибок, которые могут возникнуть, если вы случайно забудете закрыть файл.
Давайте попробуем переписать наш пример, используя ключевое слово with :
with open("demo.txt") as file: print(file.read())
Что такое метод readline() в Python?
Этот метод читает одну строку из файла и возвращает ее.
В следующем примере у нас есть текстовый файл с двумя предложениями:
This is the first line This is the second line
Если мы воспользуемся методом readline() , он выведет нам только первое предложение нашего файла.
with open("demo.txt") as file: print(file.readline()) # Output: # This is the first line
Этот метод также принимает необязательный параметр размера. Мы можем изменить наш пример, добавив число 7. В таком случае программа считает и выведет нам только фразу This is :
with open("demo.txt") as file: print(file.readline(7))
Что такое метод readlines() в Python?
Этот метод читает и возвращает список всех строк в файле.
Предположим, у нас есть текстовый файл demo.txt со списком покупок:
Grosery Store List: Chicken Mango Rice Chocolate Cake
В следующем примере давайте выведем наши продукты в виде списка с помощью метода readlines() .
with open("demo.txt") as file: print(file.readlines()) # Output: # ['Grocery Store List:\n', 'Chicken\n', 'Mangos\n', 'Rice\n', 'Chocolate Cake\n']
Как прочитать текстовый файл при помощи цикла for
В качестве альтернативы методам чтения можно использовать цикл for .
Давайте распечатаем все элементы файла demo.txt, перебирая объект в цикле for .
with open("demo.txt") as file: for item in file: print(item)
Запустим наш код и получим следующий результат:
# Output: # Grocery Store List: # Chicken # Mango # Rice # Chocolate Cake
Заключение
Итак, если вы хотите прочитать текстовый файл в Python, вам сначала нужно его открыть.
open("name of file you want opened", "optional mode")
Если текстовый файл и ваш текущий файл, где вы пишете код, находятся в одной директории, можно просто указать имя файла в функции open() .
Если ваш текстовый файл находится в другом каталоге, вам необходимо указать правильный путь к нему.
Функция open() принимает необязательный параметр режима. Режим по умолчанию – чтение ( «r» ).
Чтобы проверить, можно ли прочитать текстовый файл, вы можете использовать метод readable() . Он возвращает True , если файл можно прочитать, или False в противном случае.
Метод read() будет читать все содержимое файла как одну строку.
Также, когда вы закончите читать файл, не забудьте закрыть его. Один из способов убедиться, что ваш файл закрыт, – использовать ключевое слово with . Оно закрывает файл автоматически и вам не нужно беспокоиться об этом.
Метод readline() будет считывать только одну строку из файла и возвращать ее.
Метод readlines() прочитает и вернет все строки в файле в виде списка.
Также для чтения содержимого файлов можно использовать цикл for .
Надеемся, вам понравилась эта статья. Желаем удачи в вашем путешествии по миру Python!
Python Open File – How to Read a Text File Line by Line
In Python, there are a few ways you can read a text file.
In this article, I will go over the open() function, the read() , readline() , readlines() , close() methods, and the with keyword.
What is the open() function in Python?
If you want to read a text file in Python, you first have to open it.
This is the basic syntax for Python’s open() function:
open("name of file you want opened", "optional mode")
File names and correct paths
If the text file and your current file are in the same directory («folder»), then you can just reference the file name in the open() function.
Here is an example of both files being in the same directory:
If your text file is in a different directory, then you will need to reference the correct path name for the text file.
In this example, the random-text file is inside a different folder then main.py :
In order to access that file in the main.py , you have to include the folder name with the name of the file.
open("text-files/random-text.txt")
If you don’t have the correct path for the file, then you will get an error message like this:
It is really important to keep track of which directory you are in so you can reference the correct path name.
Optional Mode parameter in open()
There are different modes when you are working with files. The default mode is the read mode.
The letter r stands for read mode.
You can also omit mode= and just write «r» .
There are other types of modes such as «w» for writing or «a» for appending. I am not going to go into detail for the other modes because we are just going to focus on reading files.
For a complete list of the other modes, please read through the documentation.
Additional parameters for the open() function in Python
The open() function can take in these optional parameters.
To learn more about these optional parameters, please read through the documentation.
What is the readable() method in Python?
If you want to check if a file can be read, then you can use the readable() method. This will return a True or False .
This example would return True because we are in the read mode:
file = open("demo.txt") print(file.readable())
If I changed this example, to «w» (write) mode, then the readable() method would return False :
file = open("demo.txt", "w") print(file.readable())
What is the read() method in Python?
The read() method is going to read all of the content of the file as one string. This is a good method to use if you don’t have a lot of content in the text file.
In this example, I am using the read() method to print out a list of names from the demo.txt file:
file = open("demo.txt") print(file.read())
This method can take in an optional parameter called size. Instead of reading the whole file, only a portion of it will be read.
If we modify the earlier example, we can print out only the first word by adding the number 4 as an argument for read() .
file = open("demo.txt") print(file.read(4))
If the size argument is omitted, or if the number is negative, then the whole file will be read.
What is the close() method in Python?
Once you are done reading a file, it is important that you close it. If you forget to close your file, then that can cause issues.
This is an example of how to close the demo.txt file:
file = open("demo.txt") print(file.read()) file.close()
How to use the with keyword to close files in Python
One way to ensure that your file is closed is to use the with keyword. This is considered good practice, because the file will close automatically instead of you having to manually close it.
Here is how to rewrite our example using the with keyword:
with open("demo.txt") as file: print(file.read())
What is the readline() method in Python?
This method is going to read one line from the file and return that.
In this example, we have a text file with these two sentences:
This is the first line This is the second line
If we use the readline() method, it will only print the first sentence of the file.
with open("demo.txt") as file: print(file.readline())
This method also takes in the optional size parameter. We can modify the example to add the number 7 to only read and print out This is :
with open("demo.txt") as file: print(file.readline(7))
What is the readlines() method in Python?
This method will read and return a list of all of the lines in the file.
In this example, we are going to print out our grocery items as a list using the readlines() method.
with open("demo.txt") as file: print(file.readlines())
How to use a for loop to read lines from a file in Python
An alternative to these different read methods would be to use a for loop .
In this example, we can print out all of the items in the demo.txt file by looping over the object.
with open("demo.txt") as file: for item in file: print(item)
Conclusion
If you want to read a text file in Python, you first have to open it.
open("name of file you want opened", "optional mode")
If the text file and your current file are in the same directory («folder»), then you can just reference the file name in the open() function.
If your text file is in a different directory, then you will need to reference the correct path name for the text file.
The open() function takes in the optional mode parameter. The default mode is the read mode.
If you want to check if a file can be read, then you can use the readable() method. This will return a True or False .
The read() method is going to read all of the content of the file as one string.
Once you are done reading a file, it is important that you close it. If you forget to close your file, then that can cause issues.
One way to ensure that your file is closed is to use the with keyword.
with open("demo.txt") as file: print(file.read())
The readline() method is going to read one line from the file and return that.
The readlines() method will read and return a list of all of the lines in the file.
An alternative to these different read methods would be to use a for loop .
with open("demo.txt") as file: for item in file: print(item)
I hope you enjoyed this article and best of luck on your Python journey.