IO
input
value = input('Input an integer number: ')
print(type(value)) # str
print(int(value)*100)
Read
# open file
'''
1234567
abcdefg
'''
f = open('data.txt', 'rb')
# read line by line
for line in f:
print(line)
# offset, from
# from, 0, start of the file, 1, current position, 2, end of the file
f.seek(0, 0)
# read line by line with index
for index, line in enumerate(f):
print(index, line)
# back to starting position
f.seek(0, 0)
# display the current position
print(f.tell(), f.read(2)) # read two characters
print(f.tell(), f.read()) # read to the end
# read line by line
f.seek(0, 0)
try:
while True:
print(next(f)) # raise StopIteration when hit EOF
except StopIteration:
pass
f.seek(0, 0)
# read character by character
while True:
c = f.read(1)
if not c:
break
print("%10s, %10d" % (c, ord(c)))
# close file
f.close()
Write
# open file
f = open('data.txt', 'r')
o = open('temp.txt', 'w')
# read line by line
for index, line in enumerate(f):
s = '{:10d} {}'.format(index, line)
o.write(s)
f.close()
o.close()
File Attributes
# open file
f = open('data.txt', 'rb')
# file attributes
print(f.closed)
print(f.mode) # rb
print(f.name) # data.txt
# close file
f.close()
Open and Close File
import sys
try:
f = open('temp.txt', 'w+')
f.write('Hello')
except OSError as argument:
print(argument)
finally:
if 'f' in locals():
print('Close the opened file ...')
f.close()
else:
print('Can not close file ...')
with open('data.txt', 'rb') as f:
# read line by line
for line in f:
print(line)
Encoding
f = open('data.txt', 'rb', encoding='utf-8')
# close file
f.close()
Unicode and Byte String
f = open('welcome.txt', 'r', encoding = 'utf-8')
o = open('output.txt', 'w')
for line in f:
print(type(line)) # str, unicode
o.write(line)
o.close()
f.close()
f = open('welcome.txt', 'rb')
o = open('output.txt', 'wb')
for line in f:
print(type(line)) # bytes, byte string
o.write(line)
o.close()
f.close()
File Name and Line Index
# i11.py
from inspect import currentframe, getframeinfo
def info():
frameinfo = getframeinfo(currentframe())
return frameinfo.filename, frameinfo.lineno
import i11
filename, line_index = i11.info()
print(filename, line_index)
Reference