473,659 Members | 2,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do i read just the last line of a text file?

Hey there.
i want to set a variable to represent the last line of a text file
how do i do that?
or even better, how do i create a list of the lines of a text file?

Jul 19 '05 #1
8 2340
nephish wrote:
Hey there.
i want to set a variable to represent the last line of a text file
how do i do that?
or even better, how do i create a list of the lines of a text file?


Hey there to you too.

According to the manual
http://www.python.org/doc/2.4.1/lib/...e-objects.html

readlines([sizehint])
Read until EOF using readline() and return a list containing
the lines thus read.

Which part of this don't you understand?

Jul 19 '05 #2
On Sun, 29 May 2005 at 04:42 GMT, nephish wrote:
Hey there.
i want to set a variable to represent the last line of a text file
how do i do that?
or even better, how do i create a list of the lines of a text file?


from sys import argv ## Import argv from sys module

file = open(argv[1]) ## Open the file given on the command line
all_lines = file.readlines( ) ## Read all the lines
last_line = all_lines[-1] ## Assign the last line
--
Chris F.A. Johnson <http://cfaj.freeshell. org>
=============== =============== =============== =============== ======
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
<http://www.torfree.net/~chris/books/cfaj/ssr.html>
Jul 19 '05 #3
Chris F.A. Johnson wrote:

file = open(argv[1]) ## Open the file given on the command line
all_lines = file.readlines( ) ## Read all the lines


I see your shadowing and raise you one obfuscation:

open = file(argv[1]) ## File the open given on the command line
all_lines = open.readlines( ) ## Read all the lines
Jul 19 '05 #4
On Sun, 29 May 2005 at 05:57 GMT, John Machin wrote:
Chris F.A. Johnson wrote:
file = open(argv[1]) ## Open the file given on the command line
all_lines = file.readlines( ) ## Read all the lines
I see your shadowing and raise you one obfuscation:


;)
open = file(argv[1]) ## File the open given on the command line
all_lines = open.readlines( ) ## Read all the lines


Such verbosity! (I excuse mine on the grounds that it was my first
attempt at a Python program.)

all_lines = file(argv[1]).readlines()

And to answer the question in the subject line:

last_line = file(argv[1]).readlines()[-1]

Both of which assume "from sys import argv".
Now I have to get serious and forget those bad habits.

--
Chris F.A. Johnson <http://cfaj.freeshell. org>
=============== =============== =============== =============== ======
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
<http://www.torfree.net/~chris/books/cfaj/ssr.html>
Jul 19 '05 #5
Chris F.A. Johnson wrote:
On Sun, 29 May 2005 at 05:57 GMT, John Machin wrote:
Chris F.A. Johnson wrote:

file = open(argv[1]) ## Open the file given on the command line
all_lines = file.readlines( ) ## Read all the lines


I see your shadowing and raise you one obfuscation:

;)

open = file(argv[1]) ## File the open given on the command line
all_lines = open.readlines( ) ## Read all the lines

Such verbosity! (I excuse mine on the grounds that it was my first
attempt at a Python program.)

all_lines = file(argv[1]).readlines()

And to answer the question in the subject line:

last_line = file(argv[1]).readlines()[-1]

Both of which assume "from sys import argv".
Now I have to get serious and forget those bad habits.


What if a file is long enough?

A.
Jul 19 '05 #6
Andy Leszczynski wrote:
Chris F.A. Johnson wrote:
And to answer the question in the subject line:

last_line = file(argv[1]).readlines()[-1]

Both of which assume "from sys import argv".


What if a file is long enough?


Huh? You mean what if it's too big to fit in memory? Then try this:

for last_line in file(argv[1]):
pass

At the end of the for loop, last_line should be bound to the last line
in the file. (If there's a chance your file might not have any lines,
you'll want to do some error checking...)

STeVe
Jul 19 '05 #7
cool. thanks for the help guys !

Jul 19 '05 #8

"Andy Leszczynski"
What if a file is long enough?


I believe you meant "What if a file is too long to read all into memory at
once?"

If the file is randomly accessible (with file.seek() backwards from the
end) then you can read a chunk at the end that you expect to be large
enough to contain the last line and search backwards for \n (ignoring a
terminating \n) to find the end of the next-to-last line. Even if the file
will fit in memory, this may be faster.

Terry J. Reedy

Jul 19 '05 #9

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

Similar topics

6
30969
by: sea | last post by:
I have text files in the following format: 123,34, ,345,890, 123,23 .. .. .. As you can see, the problem is that (1) the commas can occur in
3
2658
by: John Flynn | last post by:
hi, having problems reading from and writing back to the same file. basically, i want to read lines of text from a file and reverse them and write them back to the same file.. it has to replace the text its reversing eg.
0
683
by: Jerry | last post by:
Below is ALL the code for all the databases... Here's the problem: I callup the aspx file in IE and the form comes up just fine. When I select a person to update, I get the subject error. Aparently, when I select a person, it's not selecting anyone and returning this error. Here's the full error: Description: An unhandled exception occurred during the execution of the
3
5219
by: JenHu | last post by:
Hi, I want read line by line and characters. The characters are fix length text file, no specific delimited method between each fields. The first line is header line, the last line is footer. Between the first line and last line is the content, and I will have to load the content to database. How to read line by line? I use For lineNum = LBound(lines) To (UBound(lines) - 1) which generate error because it does read the
35
11418
by: RyanS09 | last post by:
Hello- I am trying to write a snippet which will open a text file with an integer on each line. I would like to read the last integer in the file. I am currently using: file = fopen("f.txt", "r+"); fseek(file, -2, SEEK_END); fscanf(file, "%d", &c); this works fine if the integer is only a single character. When I get into larger numbers though (e.g. 502) it only reads in the 2. Is there
9
5204
by: Adi | last post by:
Hello eveyone, I wanna ask a very simple question here (as it was quite disturbing me for a long time.) My problem is to read a file line by line. I've tried following implementations but still facing problems: Assume that FILE* filePointer; unsigned char lineBuffer;
9
2976
by: =?Utf-8?B?QnJpYW4gQ29vaw==?= | last post by:
I want to open a text file and format it into a specific line and then apply color to a specific location of the text and then display it in a RichTextBox after all of this is done. I can do all of the above after the file is loaded into the RichTextBox, and I am trying to speed the process up by doing it in a temp file.
13
25763
by: youngjin.michael | last post by:
Hello, I am new to Python and have one simple question to which I cannot find a satisfactory solution. I want to read text line-by-line from a text file, but want to ignore only the first line. I know how to do it in Java (Java has been my primary language for the last couple of years) and following is what I have in Python, but I don't like it and want to learn the better way of doing it.
4
3401
by: Keith G Hicks | last post by:
I'm trying to read a text file and alter the contents of specific lines in the file. I know how to use streamreader to read each line of a file. I'm doing that already to get the data into a database. What I need help with is on how to locate a specific line in the file, change it and then save the updated text file. Can anyone help me out or point me to a site that explains this clearly? Here's part of my code that reads the contents of...
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2750
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.