Python 3 教程 在线

1148Python3 输入和输出

将 mode 设置为 w+ 或 a+ 时,发现直接进行读操作,得到的内容都是空,但原因不太相同:

如果 mode 设置为 w+,即使没有执行 write 操作,也会将文件内容清空,因此这个时候直接进行读草稿,读到的是空内容。

f = open("E:\\administrator\\Desktop\\test.txt", "w+")

如果 mode 设置为 a+,文件指针位置默认在最后面,因为读内容时,是按照指针的位置往后读,所以如果指针位置在最后,那读出来的是空,在读之前,一定要注意确认好指针位置是对的。

f = open("E:\\administrator\\Desktop\\test.txt", "a+")
f.write("append content")
print(f.tell())  #此时指针在文件字符末尾处
f.seek(0)
print(f.tell())  # 指针回到0的位置
str = f.read()
print(str)
f.close()f = open("E:\\administrator\\Desktop\\test.txt", "w+")

1147Python3 输入和输出

格式化输出

1、整数的输出

语法说明

格式化符号格式说明备注 %o 八进制 oct%d 十进制 dec%x 十六进制 hex。

举个栗子

print('%o' % 20) # 八进制24
print('%d' % 20) # 十进制20
print('%x' % 24) # 十六进制18

2、浮点数输出

语法说明

格式化符号说明备注 %f 保留小数点后面六位有效数字 float%e 保留小数点后面六位有效数字 %g 在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法。

举个栗子:

print('%f' % 1.11)         # 默认保留6位小数1.110000
print('%.1f' % 1.11)       # 取1位小数1.1
print('%e' % 1.11)         # 默认6位小数,用科学计数法1.110000e+00
print('%.3e' % 1.11)       # 取3位小数,用科学计数法1.110e+00
print('%g' % 1111.1111)    # 默认6位有效数字1111.11
print('%.7g' % 1111.1111)  # 取7位有效数字1111.111
print('%.2g' % 1111.1111)  # 取2位有效数字,自动转换为科学计数法1.1e+03

3、字符串输出

语法说明

格式化符号说明备注 %s 字符串输出 string%10s 右对齐,占位符 10位%-10s 左对齐,占位符 10 位 %.2s 截取 2 位字符串 %10.2s10 位占位符,截取两位字符串。

举个栗子:

print('%s' % 'hello world')       # 字符串输出hello world
print('%20s' % 'hello world')     # 右对齐,取20位,不够则补位         hello world
print('%-20s' % 'hello world')    # 左对齐,取20位,不够则补位hello world         
print('%.2s' % 'hello world')     # 取2位he
print('%10.2s' % 'hello world')   # 右对齐,取2位        he
print('%-10.2s' % 'hello world')  # 左对齐,取2位he

1146Python3 输入和输出

通过 pickle 序列化实现一个简单联系人信息管理:

import pickle
import os

datafile = 'person.data'
line = '======================================='
message = '''
=======================================
Welcome bookmark:
    press 1 to show list
    press 2 to add pepole
    press 3 to edit pepole
    press 4 to delete pepole
    press 5 to search pepole
    press 6 to show menu
    press 0 to quit
=======================================
'''
print(message)

class Person(object):
    """通讯录联系人"""
    def __init__(self, name, number):
        self.name = name
        self.number = number

# 获取数据
def get_data(filename=datafile):
    # 文件存在且不为空
    if os.path.exists(filename) and os.path.getsize(filename):
        with open(filename,'rb') as f:
            return pickle.load(f)
    return None
        
# 写入数据
def set_data(name, number, filename=datafile):

    personList = {} if get_data() == None else get_data()

    with open(filename,'wb') as f:
        personList[name] = Person(name,number)
        pickle.dump(personList,f)

# 保存字典格式的数据到文件
def save_data(dictPerson, filename=datafile):
    with open(filename,'wb') as f:
        pickle.dump(dictPerson,f)

# 显示所有联系人
def show_all():
    personList = get_data()
    if personList:
        for v in personList.values():
            print(v.name,v.number)
        print(line)
    else:
        print('not yet person,please add person')
        print(line)

# 添加联系人
def add_person(name,number):
    set_data(name,number)
    print('success add person')
    print(line)

# 编辑联系人
def edit_person(name,number):
    personList = get_data()
    if personList:
        personList[name] = Person(name,number)
        save_data(personList)
        print('success edit person')
        print(line)

# 删除联系人
def delete_person(name):
    personList = get_data()
    if personList:
        if name in personList:
            del personList[name]
            save_data(personList)
            print('success delete person')
        else:
            print(name,' is not exists in dict')
        print(line)


# 搜索联系人
def search_person(name):
    personList = get_data()
    if personList:
        if name in personList.keys():
            print(personList.get(name).name, personList.get(name).number)
        else:
            print('No this person of ',name)
        print(line)
        

while True:
    num = input('>>')

    if num == '1':
        print('show all personList:')
        show_all()
    elif num == '2':
        print('add person:')    
        name = input('input name>>')
        number = input('input number>>')
        add_person(name,number)
    elif num == '3':
        print('edit person:')
        name = input('input name>>')
        number = input('input number>>')
        edit_person(name,number)
    elif num == '4':
        print('delete person:')
        name = input('input name>>')
        delete_person(name)
    elif num == '5':
        print('search :')
        name = input('input name>>')
        search_person(name)
    elif num == '6':
        print(message)
    elif num == '0':
        break
    else:
        print('input error, please retry')

1145Python3 输入和输出

input() 默认输入的为 str 格式,若用数学计算,则需要转换格式,例:

a=input('请输入数字:')
print(a*2)

假设输入数值为3,则上例中得出结果为:

33

若将代码修改为:

a=int(input('请输入数字:'))
print(a*2)

则结果为:

6

1144Python3 输入和输出

python文件写入也可以进行网站爬虫,我的python版本是3.6,以下代码是打开project.txt文件,并向里面写入http://www.baidu.com网站代码。

from urllib import request

response = request.urlopen("http://www.baidu.com/")  # 打开网站
fi = open("project.txt", 'w')                        # open一个txt文件
page = fi.write(str(response.read()))                # 网站代码写入
fi.close()                                           # 关闭txt文件