views:

136

answers:

3

Hello everyone, can someone help me do this :

I first open a file:

Date=open('Test.txt','r')

but what I am looking for is how to read line number 12, then check if it contains the word "Hey!", and in that case print "Found Word", otherwise print "not found" and write "Hello Dude" after 30 letters.

+3  A: 

Here are a couple of approaches you could use:

  • Read all lines by using f.readlines() and index in to the returned list.
  • Read each line one at a time in a loop and keep a count of how many lines you have read so far.
Mark Byers
i don't want readlines !! i heard about seek() but i don't know
Str1k3r
What is your quarrel with readlines()?
Jim Brissom
@Jim Possibly, the teacher said "don't use `readlines()`". Or "The purpose of the next exercise is to use `seek()`".
Adriano Varoli Piazza
well about write in line number 30 for example !! how to do it ?
Str1k3r
@Str1k3r, you're not displaying any sign of actually trying.
Adriano Varoli Piazza
+8  A: 

You can use the linecache built-in module to directly read line 12 from a text file:

import linecache
print(linecache.getline("Test.txt", 12))

You can look for text within a string using in:

text = linecache.getline("Test.txt", 12)
if "Hey!" in text:
    print("Found word")
else:
    print("not found")
Greg Hewgill
You are just enabling him, you know :)
Adriano Varoli Piazza
+1 didn't know about linecache.
Mark Byers
@Adriano: In this case, "disabling" is probably more apt.
Glenn Maynard
+4  A: 

See Python's excellent online docs, specifically (what I'm pointing you to) those for the built-in function open:

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file).

Since you want to read the existing file you don't want to truncate it, and since you want to write over it at a specific byte offset you don't want the append-update mode either, so it should be pretty obvious which of the three "open for updating" modes you want to use, right? Just pass it as the second argument to open (the first one being the file's name or path).

The open function gives you a file object, on which you can call the seek method to change the position for the next read or write, and tell (documented right after it at the URL I just pointed you to) if you need to know the current position at any time.

Alex Martelli
Very good answer!
Adriano Varoli Piazza