Difference between revisions of "Perform IO with Text Files"

From rbachwiki
Jump to navigation Jump to search
(Created page with "==Opening a File== myfile= open('filename.txt') myfile.read() # reads a string of everything in the file myfile.seek(0) # reset the cursor to the top of the file contents...")
 
 
(3 intermediate revisions by the same user not shown)
Line 9: Line 9:
   contents = my_new_file.read()
   contents = my_new_file.read()


  ==File Locations==
Open ReadOnly
  with open('myfile.txt', mode= 'r') as myfile:
  contents = myfile.read()
 
Available Modes:
mode-'r' Read only
mode='w' write only (will overwrite files or create new)
mode= 'a' append only (will add to a file)
mode = 'r+' reading and writing
mode= 'w+' is writing and reading (Overwrites existing files or crates a new file)
==[[#top|Back To Top]] - [[Python|Category]]==
[[Category:Python]]

Latest revision as of 16:19, 1 September 2020

Opening a File

myfile= open('filename.txt')
myfile.read() # reads a string of everything in the file
myfile.seek(0) # reset the cursor to the top of the file
contents = myfile.read()
myfile.readlines() # will read lines as a list
myfile.close() # closes the file
with open('filename.txt') as my_new_file:
 contents = my_new_file.read()

Open ReadOnly

with open('myfile.txt', mode= 'r') as myfile:
 contents = myfile.read()

Available Modes:

mode-'r' Read only
mode='w' write only (will overwrite files or create new)
mode= 'a' append only (will add to a file)
mode = 'r+' reading and writing
mode= 'w+' is writing and reading (Overwrites existing files or crates a new file)

Back To Top - Category