Hi,
I have to search for a string on a big file. Once this string is
found, I would need to get the number of the line in which the string
is located on the file. Do you know how if this is possible to do in
python ?
Thanks 11 21176
-On [20080108 09:21], Horacius ReX (ho**********@g mail.com) wrote:
>I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ?
(Assuming ASCII, otherwise check out codecs.open().)
big_file = open('bigfile.t xt', 'r')
line_nr = 0
for line in big_file:
line_nr += 1
has_match = line.find('my-string')
if has_match 0:
print 'Found in line %d' % (line_nr)
Something to this effect.
--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org/ asmodai
イェルーン ラウフãƒ*ッ ク ヴァン デル ウェルヴェ ン http://www.in-nomine.org/ | http://www.rangaku.org/
If you think that you know much, you know little...
On Jan 8, 7:33 pm, Jeroen Ruigrok van der Werven <asmo...@in-
nomine.orgwrote :
-On [20080108 09:21], Horacius ReX (horacius....@g mail.com) wrote:
I have to search for a string on a big file. Once this string is
found, I would need to get the number of the line in which the string
is located on the file. Do you know how if this is possible to do in
python ?
(Assuming ASCII, otherwise check out codecs.open().)
big_file = open('bigfile.t xt', 'r')
line_nr = 0
for line in big_file:
line_nr += 1
has_match = line.find('my-string')
if has_match 0:
Make that >=
| >>'fubar'.find( 'fu')
| 0
| >>>
print 'Found in line %d' % (line_nr)
-On [20080108 09:51], John Machin (sj******@lexic on.net) wrote:
>Make that >=
Right you are. Sorry, was doing it quickly from work. ;)
And I guess the find will also be less precise if the word you are looking is
a smaller part of a bigger word. E.g. find 'door' in a line that has 'doorway'
in it.
So 't is merely for inspiration. ;)
--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org/ asmodai
イェルーン ラウフãƒ*ッ ク ヴァン デル ウェルヴェ ン http://www.in-nomine.org/ | http://www.rangaku.org/
>From morning to night I stayed out of sight / Didn't recognise I'd become
No more than alive I'd barely survive / In a word, overrun...
-On [20080108 09:51], John Machin (sj******@lexic on.net) wrote:
>Make that >=
| >>'fubar'.find( 'fu')
Or even just:
if 'my-string' in line:
...
Same caveat emptor applies though.
--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org/ asmodai
イェルーン ラウフãƒ*ッ ク ヴァン デル ウェルヴェ ン http://www.in-nomine.org/ | http://www.rangaku.org/
We're walking this earth. We're walking this shining earth...
Jeroen Ruigrok van der Werven wrote:
-On [20080108 09:21], Horacius ReX (ho**********@g mail.com) wrote:
>>I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ?
(Assuming ASCII, otherwise check out codecs.open().)
big_file = open('bigfile.t xt', 'r')
line_nr = 0
for line in big_file:
line_nr += 1
has_match = line.find('my-string')
if has_match 0:
print 'Found in line %d' % (line_nr)
Something to this effect.
apart from that look at the linecache module. If it's a big file it could
help you with subsequent access to the line in question
hth
martin
-- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours
You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.
On Behalf Of Horacius ReX
I have to search for a string on a big file. Once this string
is found, I would need to get the number of the line in which
the string is located on the file. Do you know how if this is
possible to do in python ?
This should be reasonable:
>>for num, line in enumerate(open( "/python25/readme.txt")):
if "Guido" in line:
print "Found Guido on line", num
break
Found Guido on line 1296
>>>
Regards,
Ryan Ginstrom
Jeroen Ruigrok van der Werven wrote:
line_nr = 0
for line in big_file:
line_nr += 1
has_match = line.find('my-string')
if has_match 0:
print 'Found in line %d' % (line_nr)
Style note:
May I suggest enumerate (I find the explicit counting somewhat clunky)
and maybe turning it into a generator (I like generators):
def lines(big_file, pattern="my string"):
for n, line in enumerate(big_f ile):
if pattern in line:
print 'Found in line %d' % (n)
yield n
or for direct use, how about a simple list comprehension:
lines = [n for (n, line) in enumerate(big_f ile) if "my string" in line]
(If you're just going to iterate over the result, that is you do not
need indexing, replace the brackets with parenthesis. That way you get a
generator and don't have to build a complete list. This is especially
useful if you expect many hits.)
Just a note.
regards
/W
-On [20080108 12:59], Wildemar Wildenburger (la*********@kl apptsowieso.net ) wrote:
>Style note: May I suggest enumerate (I find the explicit counting somewhat clunky) and maybe turning it into a generator (I like generators):
Sure, I still have a lot to discover myself with Python.
I'll study your examples, thanks. :)
--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org/ asmodai
イェルーン ラウフãƒ*ッ ク ヴァン デル ウェルヴェ ン http://www.in-nomine.org/ | http://www.rangaku.org/
A conclusion is simply the place where you got tired of thinking...
>I have to search for a string on a big file. Once this string
>is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is possible to do in python ?
This should be reasonable:
>>>for num, line in enumerate(open( "/python25/readme.txt")):
if "Guido" in line:
print "Found Guido on line", num
break
Found Guido on line 1296
Just a small caveat here: enumerate() is zero-based, so you may
actually want add one to the resulting number:
s = "Guido"
for num, line in enumerate(open( "file.txt") ):
if s in line:
print "Found %s on line %i" % (s, num + 1)
break # optionally stop looking
Or one could use a tool made for the job:
grep -n Guido file.txt
or if you only want the first match:
sed -n '/Guido/{=;p;q}' file.txt
-tkc This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: lecichy |
last post by:
Hello
Heres the situation:
I got a file with lines like:
name:second_name:somenumber:otherinfo
etc with different values between colons ( just like passwd file)
What I want is to extract some part of it like all names or numbers from
each line, simply text fom between e.g. second and third colon. And turn it
|
by: Venkat |
last post by:
Hi All,
I want to typecast int to std::string how can i do it.
Here is the sample code.
int NewList;
//Fill the NewList with integers values.
.......
|
by: Sharon |
last post by:
hi,
I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4
how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?
|
by: aton1 |
last post by:
Hi, i have some questions regarding the use of datatype string in C++. I use g++ compiler and also use .ccmalloc to test for the memory leak.
Here is a simple program that i have wrote which ccmalloc reports that there is a memory leak:
line 1: #include <iostream>
line 2:
line 3: using namespace std;
line 4:
line 5: int main(int argc, char **argv)
line 6: {
|
by: Freaker85 |
last post by:
Hello,
I am new at programming in C and I am searching a manner to parse a
string into an integer.
I know how to do it in Java, but that doesn't work in C ;o)
I searched the internet but I didn't found it yet.
help please
thank you
Freaker85
| |
by: Tigerlily |
last post by:
Hello! I need to count the number of words in a string read in from an infile, in a function, but I don't know how to do this. This is what I have so far.
//Tiffany Lynn Goodseit
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void diffwords(string &line);
int main()
|
by: elliotng.ee |
last post by:
I have a text file that contains a header 32-bit binary. For example,
the text file could be:
%%This is the input text
%%test.txt
Date: Tue Dec 26 14:03:35 2006
00000000000000001111111111111111
11111111111111111111111111111111
00000000000000000000000000000000
11111111111111110000000000000000
|
by: Ameet Nanda |
last post by:
Hi All,
I access net using a proxy, which I have to authenticate everytime I try
to access net from my system. Now when I use urllib2.urlopen(url) , I
cant get ahead. I must provide proxy authentication , I tried reading
docs online which speak of something called as FancyUrlOpener. Now i
want to hardcode my username and password inside the script or somehow
save it.
How do I go ahead with that ??
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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,...
|
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...
| |
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,...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |