Advertisement
jspill

webinar-files-2022-01-15

Jan 15th, 2022
1,189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # Webinar: Working with Files 2022 01 15
  2.  
  3. # open the file and assign to var
  4.  
  5. # older syntax
  6. f = open("test.txt", "r")
  7. # work with the file
  8. f.close()
  9.  
  10. # newer syntax, the with/open block
  11. with open("test.txt", "r") as f:
  12.     # work with file
  13.     # two ways to grab contents .read() and .readlines()
  14.     #myString = f.read() # returns it all as one string
  15.     myList = f.readlines() # returns a list of strings by line, much like str.split()
  16.  
  17. # print(myString)
  18. # print(myList)
  19. for line in myList:
  20.     print(line.rstrip(), end=" ") # rstrip()!
  21.  
  22. # When dealing with string input in general, and especially from files,
  23. # start to expect that there will be whitespace characters like line returns you don't want!
  24.  
  25. # The string .strip() and rstrip() methods are great for this!
  26. # It's a good idea to use them almost by default.
  27. # If there's no trailing whitespace, rstrip() doesn't cause any problems
  28.  
  29. with open("mock_data.csv", "r") as f:
  30.     # print(f.readlines())
  31.     myList = f.readlines()
  32. for line in myList:
  33.     print(line.rstrip().split(",")[3])
  34.  
  35. # WRITE mode is destructive. It will create a file if it doesn't exist, or overwrite if it does
  36. with open("file123.txt", "w") as f:
  37.     f.write("I am writing to this file.") # from last playhead position...:
  38.     f.write("And I wrote more.") # "I am writing to this file.And I wrote more."
  39.  
  40. # APPEND mode writes non-destructively, starting at end of file
  41. # let's use new line returns in this version...
  42. with open("file123.txt", "a") as f:
  43.     f.write("\nI am writing to this file.")
  44.     f.write("\nAnd I wrote more.")
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement