ClavinJune

Searching word in a file

Apr 24th, 2017
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. #importing sys for automatically exit if there's error
  2. import sys
  3.  
  4. #inputing file
  5. file_name = raw_input("Input your file name you want to read : ")
  6.  
  7. #search file, exit when there's no file
  8. try:
  9.     file = open(file_name, 'r')
  10. except:
  11.     print "No such files"
  12.     sys.exit(2)
  13.  
  14. #inputting keyword
  15. word = raw_input("Input your text : ")
  16.  
  17. #making lists of string
  18. strings = []
  19.  
  20. #reading every char in file
  21. for string in file.read():
  22.     #append every char into lists
  23.     strings.append(string)
  24.  
  25. #joining every char to one string
  26. strings =  ''.join(str(e) for e in strings)
  27.  
  28. #splitting every word by \n
  29. strings = strings.split('\n')
  30.  
  31. #checking every word in lists
  32. for string in strings:
  33.     if word == string:
  34.         print word + " match!"
  35.  
  36. #closing file
  37. file.close()
Add Comment
Please, Sign In to add comment