Python笔记 - 输入输出

/ 技术文章 / 0 条评论 / 510浏览

Python笔记 - 输入输出

格式化

s = 'Hello World!'

str(s)
#     'Hello World!'

repr(s)
#     "'Hello World!'"

repr()转义字符

str('hello\n')
#     'hello\n'

repr('hello\n')
#     "'hello\\n'"

右对齐rjust() 左对齐ljust()

for x in range(4, 12):
    print(repr(x).rjust(2), repr(x*x).rjust(4))
#     4   16
#     5   25
#     6   36
#     7   49
#     8   64
#     9   81
#    10  100
#    11  121	

for x in range(4, 12):
    print(repr(x).ljust(2), repr(x*x).ljust(4))
#   4  16  
#   5  25  
#   6  36  
#   7  49  
#   8  64  
#   9  81  
#   10 100 
#   11 121 
	
for x in range(4, 12):
    print(repr(x*x*x).center(5))
#      64 
#     125 
#     216 
#     343 
#     512 
#     729 
#     1000
#     1331

补零 zfill()

for x in range(4, 12):
    print(repr(x).zfill(2), repr(x*x).zfill(4))
#   04 0016
#   05 0025
#   06 0036
#   07 0049
#   08 0064
#   09 0081
#   10 0100
#   11 0121

str.format()

# By order
for x in range(4, 12):
    print('{0:2d} {1:4d}'.format(x, x*x))
#     4   16
#     5   25
#     6   36
#     7   49
#     8   64
#     9   81
#    10  100
#    11  121	
# By name
for x in range(9, 12):
    print('{num:2d} {squa:4d}'.format(squa=x * x, num =x))
#     9   81
#    10  100
#    11  121

'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr())

print('asc: {!a}, string: {!s}, String: {!r}'.format(55, '55\n', '55\n'))

#    asc: 55, string: 55
#    , String: '55\n'

读取键盘输入

ss = input('Please input something:')
print ('Content: ', ss)
#   Please input something:Hello
#   Content:  Hello

读写文件

open(filename, mode)
moderr+ww+aa+
**-*-*
-*****
新建--****
覆盖--**--
指向头+***--
指向尾----**

后面带b(比如 rb, wb+)表示按二进制格式打开

f = open('./test.txt', 'w')
f.write('This is a test line!\n')
f.close()
f = open('./test.txt', 'a')
f.write('This is a test line, line2!\n')
f.close()
f = open('./test.txt', 'r')
ss = f.read()
f.close()
print(ss)
#    This is a test line!
#    This is a test line, line2!

行操作

f = open('./test.txt', 'r')
ss = f.readline()
f.close()
print(ss)
#    This is a test line!

f = open('./test.txt', 'r')
list1 = f.readlines()
f.close()
print(repr(list1))
#    ['This is a test line!\n', 'This is a test line, line2!\n']

with关键字

with open('./test.txt', 'r') as f:
    list1 = f.readlines()
f.close()
print(list1[0])
#    This is a test line!

pickle 模块: 序列化 反序列化

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

print('Init data1: {0}'.format(repr(data1)))

with open('data.pkl', 'wb') as output:
    pickle.dump(data1, output)
output.close()

data1.clear()
print('Cleaned data1: {0}'.format(repr(data1)))

with open('data.pkl', 'rb') as output:
    data1 = pickle.load(output)
output.close()
print('Recover data1: {0}'.format(repr(data1)))
#    Init data1: {'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
#    Cleaned data1: {}
#    Recover data1: {'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}