python file io 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: python write to file
with open(filename,"w") as f:
f.write('Hello World')
Example 3: python file open
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')
file.close()
Example 4: python3 seek
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)
13
>>> f.read(1)
b'd'
Example 5: python write to file
with open("testfile.txt", "w") as f:
f.write("Hello World")
Example 6: with open as file python
>>> with open('workfile') as f:
... read_data = f.read()
>>>
>>> f.closed
True