Free2Code
 
Time: 2008-12-04, 09:20pm
Python find string
Subject: Python find string  ·  Posted: 2005-03-05, 05:11am
Rank: ? (1)
Member #: 23658
Hi all

So im needing a code to search for the word "hello" in all txt files in currentdir. if the txt file dont have the text "hello" then simply write "hello" into that file. hmmm well thats all i need.


thanx for any help

 
  Reply to this ·  Post link ·  Top
Subject: Re: Python find string  ·  Posted: 2006-01-04, 10:40am
Rank: ? (6)
Member #: 26285
I'm writing out of my head here, so this code will most likely not work, but you'll get the picture.

Code:
  1. import os, string
  2. for x in os.listdir("."):
  3.  work_str = open(x,"r").read()
  4.  if string.find(work_str,"hello") == -1:
  5.   open(x,"a").append("hello")
  6.  else: pass


OK, its probably the buggiest code your computer has ever seen, but you get my point (I hope Oh, and, look the code through before running it, so it doesn't kill your computer or anything.. No guarantees

PS, I opened the file twice, perhaps there's a nicer way to do this. DS

 
  Reply to this ·  Post link ·  Top

Pages: 1

Please login or register to post a reply.

icons