Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Webinar: Working with Files 2022 01 15
- # open the file and assign to var
- # older syntax
- f = open("test.txt", "r")
- # work with the file
- f.close()
- # newer syntax, the with/open block
- with open("test.txt", "r") as f:
- # work with file
- # two ways to grab contents .read() and .readlines()
- #myString = f.read() # returns it all as one string
- myList = f.readlines() # returns a list of strings by line, much like str.split()
- # print(myString)
- # print(myList)
- for line in myList:
- print(line.rstrip(), end=" ") # rstrip()!
- # When dealing with string input in general, and especially from files,
- # start to expect that there will be whitespace characters like line returns you don't want!
- # The string .strip() and rstrip() methods are great for this!
- # It's a good idea to use them almost by default.
- # If there's no trailing whitespace, rstrip() doesn't cause any problems
- with open("mock_data.csv", "r") as f:
- # print(f.readlines())
- myList = f.readlines()
- for line in myList:
- print(line.rstrip().split(",")[3])
- # WRITE mode is destructive. It will create a file if it doesn't exist, or overwrite if it does
- with open("file123.txt", "w") as f:
- f.write("I am writing to this file.") # from last playhead position...:
- f.write("And I wrote more.") # "I am writing to this file.And I wrote more."
- # APPEND mode writes non-destructively, starting at end of file
- # let's use new line returns in this version...
- with open("file123.txt", "a") as f:
- f.write("\nI am writing to this file.")
- f.write("\nAnd I wrote more.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement