Advertisement
Guest User

Lab5 P1

a guest
Apr 8th, 2020
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Mar 12 22:12:36 2020
  4.  
  5. The function isWordInFile(fileName, word), which
  6. given a string, filename, and a string, word, checks whether or not word is in the file
  7. named fileName.
  8.  
  9. @author Abdallah Wahidi
  10. """
  11.  
  12. """
  13. Checks whether or not 'word' is in the file named 'fileName'
  14. """
  15. def isWordInFile(fileName, word):
  16.     nameHandle = open(fileName, 'r')
  17.     s = nameHandle.read()
  18.     if word in s:
  19.         print('True')
  20.     else:
  21.         print('False')
  22.     nameHandle.close()
  23.    
  24. isWordInFile("test.txt", "Programming")
  25. isWordInFile("test.txt", "programming")
  26.  
  27. """
  28. A variation of Part (a) which requires
  29. reading the file line by line
  30. """
  31. def wordSearch(fileName, word):
  32.     nameHandle = open(fileName, 'r')
  33.     i = 1
  34.     for line in nameHandle:
  35.         if word in line:
  36.             print(i)
  37.         i+=1
  38.     nameHandle.close()
  39. wordSearch("test.txt", 'Programming')
  40.  
  41.  
  42. """
  43. Part C:the function duplicateLines(fileName), which given a string
  44. fileName, opens the file named fileName for reading and creates a new file whose
  45. content is like fileName but with all lines duplicated
  46. """
  47.  
  48. def duplicateLines(fileName):
  49.     assert ".txt" in fileName, "The file is not a txt file"
  50.     nameHandle = open(fileName, 'r')
  51.     newFile = open("nameDuplicated.txt", 'w')
  52.     for line in nameHandle:
  53.         newFile.write(line)
  54.         newFile.write(line)
  55.     nameHandle.close()
  56.     newFile.close()
  57.    
  58. duplicateLines("test.txt")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement