python open filemode code example
Example 1: python file open modes
r for reading
r+ opens for reading and writing (cannot truncate a file)
w for writing
w+ for writing and reading (can truncate a file)
rb for reading a binary file. The file pointer is placed at the beginning of the file.
rb+ reading or writing a binary file
wb+ writing a binary file
a+ opens for appending
ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
x open for exclusive creation, failing if the file already exists (Python 3)
Example 2: read file python
document = 'document.txt'
file = open(document, 'r')
file.seek(0)
for i in file:
k = i.strip()
print k
file.close()
with open(document) as ur:
for i in ur:
k = i.strip()
print k
Example 3: read and write to file python
file = open(“testfile.txt”, “r+”)