Как проверить, что текстовый файл существует и не пуст в Python
Я написал script для чтения текстового файла в python.
Я хотел бы проверить, существует ли файл и не является пустым файлом, но этот код дает мне ошибку.
Я также хотел бы проверить, может ли программа записывать в выходной файл.
Команда:
Ошибка:
1 ответ
Чтобы проверить, присутствует ли файл и не пуст, вам нужно вызвать комбинацию os.path.exists и os.path.getsize с условием «и». Например:
В качестве альтернативного вы также можете использовать try/except с os.path.getsize (без использования os.path.exists ), потому что он поднимает OSError , если файл не существует, или если у вас нет разрешения на доступ к файлу. Например:
Из документа Python 3 os.path.getsize() будет:
Возвращает размер, в байтах, пути. Raise OSError , если файл не существует или недоступен.
Как проверить, пуст файл или нет?
У меня есть текстовый файл.
Как я могу проверить, пусто это или нет?
10 ответов
Если у вас есть объект файла, то
И getsize() , и stat() сгенерируют исключение, если файл не существует. Эта функция вернет True / False без броска (проще, но менее надежно):
Поскольку вы не определили, что такое пустой файл. Некоторые могут считать файл с пустыми строками также пустым файлом. Поэтому, если вы хотите проверить, содержит ли ваш файл только пустые строки (любые пробельные символы, ‘\ r’, ‘\ n’, ‘\ t’) , вы можете выполнить следующий пример:
Python3
Объясните: в приведенном выше примере регулярное выражение (регулярное выражение) используется для сопоставления содержимого ( content ) файла.
В частности: для регулярного выражения: ^\s*$ в целом означает, что файл содержит только пустые строки и / или пробелы.
— ^ устанавливает позицию в начале строки
— \s соответствует любому символу пробела (равному [\ r \ n \ t \ f \ v])
— * Квантор — сопоставляет от нуля до неограниченного числа раз, столько раз, сколько возможно, возвращая при необходимости (жадный)
— $ устанавливает позицию в конце строки
Python: Three ways to check if a file is empty
In this article, we will discuss different ways to check if a file is empty i.e. its size is 0 using os.stat() or os.path.getsize() or by reading its first character.
Check if a file is empty using os.stat() in Python
Python provides a function to get the statistics about the file,
It accepts file path (string) as an argument and returns an object of the structure stat, which contains various attributes about the file at the given path. One of these attributes is st_size, which tells about the size of the file in bytes.
Let’s use this to get the size of the file ‘mysample.txt’ and if size is 0 then it means, file is empty i.e.
Frequently Asked:
As our file is empty, so the output will be,
P.S. We already had an empty file ‘mysample.txt’ in the same directory.
But we should be careful while using it because if the file doesn’t exist at the given path, then it can raise an Error i.e. FileNotFoundError,
Therefore we should first check if the file exists or not before calling os.stat(). So, let’s create a separate function to check if file exists and it is empty i.e.
Latest Python — Video Tutorial
This function first confirms if the file exists or not, if yes then it checks if its size is 0 or not (if file is empty).
Let’s use this function to check if file ‘mysample.txt’ is empty,
It confirms that file ‘mysample.txt‘ is empty.
Check if file is empty using os.path.getsize() in Python
In Python os module provides another function i.e.
It accepts the file path (a string) as an argument and returns the size of the file in bytes. If the file doesn’t exist and the given path then it raises os.error.
Let’s use this to get the size of file ‘mysample.txt‘ and if the size is 0 then it means, file is empty i.e.
As our file is empty, so the output will be,
If the file doesn’t exist at the given path, then it can raise an Error i.e. FileNotFoundError,
Therefore, we should first check if the file exists or not. If file exist then only call os.path.getsize(). We have created a function which checks if file exists or not and if it exists then check if its empty or not,
Let’s use this function to check if file ‘mysample.txt’ is empty,
It confirms that file ‘mysample.txt‘ is empty.
Check if the file is empty by reading its first character in Python
In this function, it opens the file at the given path in read-only mode, then tries to read the first character in the file.
If it is not able to read the first character then it means the file is empty else not.
How to check whether a file is empty or not
I have a text file. How can I check whether it’s empty or not?
![]()
![]()
11 Answers 11
Both getsize() and stat() will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):
![]()
If you are using Python 3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size (file size in bytes):
![]()
If for some reason you already had the file open, you could try this:
![]()
![]()
if you have the file object, then
Combining ghostdog74’s answer and the comments:
False means a non-empty file.
So let’s write a function:
![]()
Since you have not defined what an empty file is: Some might also consider a file with just blank lines as an empty file. So if you want to check if your file contains only blank lines (any white space character, ‘\r’, ‘\n’, ‘\t’), you can follow the example below:
Python 3
Explanation: the example above uses a regular expression (regex) to match the content ( content ) of the file.
Specifically: for a regex of: ^\s*$ as a whole means if the file contains only blank lines and/or blank spaces.