472,371 Members | 1,470 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,371 software developers and data experts.

Checking if a text file is blank

Greetings!

I've just started learning python, so this is probably one of those
obvious questions newbies ask.

Is there any way in python to check if a text file is blank?

What I've tried to do so far is:

f = file("friends.txt", "w")
if f.read() is True:
"""do stuff"""
else:
"""do other stuff"""
f.close()

What I *mean* to do in the second line is to check if the text file is
not-blank. But apparently that's not the way to do it.

Could someone set me straight please?
Jun 27 '08 #1
7 22014
On Apr 20, 1:04 am, elno...@gmail.com wrote:
Greetings!

I've just started learning python, so this is probably one of those
obvious questions newbies ask.

Is there any way in python to check if a text file is blank?

What I've tried to do so far is:

f = file("friends.txt", "w")
if f.read() is True:
"""do stuff"""
else:
"""do other stuff"""
f.close()

What I *mean* to do in the second line is to check if the text file is
not-blank. But apparently that's not the way to do it.

Could someone set me straight please?
The flaw in your code is that "f.read() is True" doesn't do what you
think it does.

(1) The "is" operator is a test for object IDENTITY. Two objects can
be equal but distinct
>>list1 = list2 = [1, 2, 3]
list1 is list2
True
>>list1[-1] = 4
list2
[1, 2, 4]
>>list1 = [1, 2, 3]
list2 = [1, 2, 3]
list1 is list2
False
>>list1[-1] = 4
list2
[1, 2, 3]

(2) Even if you used "f.read() == True", it still wouldn't work in
Python. Values can be true or false (in the context of an if or while
statement) without being equal to True or False.

Values that are equal to True:
True, 1, 1.0, (1+0j), decimal.Decimal(1)

Values that are true but not equal to True:
"spam", "1", (1,), [1], set([1]), {1: 2}, etc.

Values that are equal to False:
False, 0, 0.0, 0j, decimal.Decimal(0)

Values that are false but not equal to False:
"", (), [], set()

And even if you are sure that you're only dealing with values of 0 or
1, it's unnecessary to write "if x == True:". It's redundant, just
like "if (x == True) == True:" or "if ((x == True) == True) ==
True:". Just write "if x:". Or, in this specific case, "if
f.read():".

(3) While not affecting your program's correctness, it's rather
inefficient to read a gigabytes-long file into memory just to check
whether it's empty. Read just the first line or the first character.
Or use os.stat .
Jun 27 '08 #2
>
Is there any way in python to check if a text file is blank?

What I've tried to do so far is:

f = file("friends.txt", "w")
if f.read() is True:
"""do stuff"""
else:
"""do other stuff"""
f.close()

What I *mean* to do in the second line is to check if the text file is
not-blank. But apparently that's not the way to do it.

Could someone set me straight please?
You're opening your file in write mode, so it gets truncated. Add "+"
to your open mode (r+ or w+) if you want to read and write.

Here is the file docstring:

file(name[, mode[, buffering]]) -file object

Open a file. The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending. The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing. Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.
Add a 'U' to mode to open the file for input with universal newline
support. Any line ending in the input file will be seen as a '\n'
in Python. Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

'U' cannot be combined with 'w' or '+' mode.

Note: open() is an alias for file().

Also, comparison of a value with True is redundant in an if statement.
Rather use 'if f.read():'

David.
Jun 27 '08 #3
el*****@gmail.com wrote:
Greetings!

I've just started learning python, so this is probably one of those
obvious questions newbies ask.

Is there any way in python to check if a text file is blank?

What I've tried to do so far is:

f = file("friends.txt", "w")
if f.read() is True:
"""do stuff"""
else:
"""do other stuff"""
f.close()

What I *mean* to do in the second line is to check if the text file is
not-blank. But apparently that's not the way to do it.

Could someone set me straight please?

Along with the other posts ... consider using the lstat command to get
information about the file.
import os
print os.lstat("friends.txt")[6]
gives the size in bytes of friends.txt or throws an OSError if
friends.txt does not exist.

lstat is portable, it defaults to stat on Windows.
Jun 27 '08 #4
>
import os
print os.lstat("friends.txt")[6]
I prefer os.lstat("friends.txt").st_size
Jun 27 '08 #5
Hi

el*****@gmail.com wrote:
Greetings!

Is there any way in python to check if a text file is blank?

obviously there are many ways, one simple way is to check length if its
None then the file is blank.

>
What I've tried to do so far is:

f = file("friends.txt", "w")
if f.read() is True:
"""do stuff"""
else:
"""do other stuff"""
f.close()
If checking the file is blank is what you are tying to do then why do
you open the file in the write mode.


Prashanth
Jun 27 '08 #6
On Apr 20, 2:04 pm, elno...@gmail.com wrote:
Greetings!

I've just started learning python, so this is probably one of those
obvious questions newbies ask.

Is there any way in python to check if a text file is blank?

What I've tried to do so far is:

f = file("friends.txt", "w")
if f.read() is True:
"""do stuff"""
else:
"""do other stuff"""
f.close()

What I *mean* to do in the second line is to check if the text file is
not-blank. But apparently that's not the way to do it.

Could someone set me straight please?
I use os.path.getsize(path) for this purpose.
Jun 27 '08 #7
David wrote:
> import os
print os.lstat("friends.txt")[6]

I prefer os.lstat("friends.txt").st_size
MUCH easier to remember!!!!

Thanks!
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Basil Fenix | last post by:
I check data from a text file with a mdb Database using a progressbar and changing the Caption by % to indicate to the user what is happening.The file is large and takes quite a while. The problem...
6
by: Ruben | last post by:
Hello. I am trying to read a small text file using the readline statement. I can only read the first 2 records from the file. It stops at the blank lines or at lines with only spaces. I have a...
4
by: Stuk | last post by:
Hi, im false beginner in C so that`s why im writting here :). I have to write a Text Reformater, which should read data from text file every Verse. In text file may appear special directives (for...
5
by: soup_nazi | last post by:
I want to remove duplicate entries within a text file. So if I had this within a text file... Applications/Diabetic Registry/ Applications/Diabetic Registry/ Applications/Diabetic Registry/...
4
by: Andyza | last post by:
I'm using FileSystemObject to open and write to a tab delimited text file. First, I connect to a database and select some data. Then I create the text file and insert each record in the text...
0
by: erucevice | last post by:
I am trying to bcp a text file that is written out of a Java application. The text file has important order information that I need to bcp into a SQL Server 2000 database. The problem is that when...
6
by: EricR | last post by:
I am trying to bcp import a text file into a SQL Server 2000 database. The text file is coming out of a java application where order information is written to the text file. Each record is on it's...
42
by: =?Utf-8?B?UGxheWE=?= | last post by:
I have an if statement that isn't working correctly and I was wondering how I check for a blank string. My Code Example if me.fieldname(arrayIndex) = "" then ----- end if When I do this and...
2
VijaySofist
by: VijaySofist | last post by:
Hi All! I want to check whether a given text File is Already Opened or not. I am using Visual Basic 6.0 in the Windows XP OS. I am using the following code. It works for .doc, .xls and .mdb....
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.