Python3 入门专栏
http://blog.csdn.net/column/details/19679.html
标准 IO
标准输出
print 函数为标准流输出函数,默认输出是换行的,如果需要不换行的输出,需要在 print 函数入参变量加上 end=“”:
val1 = "a"val2 = "b"# 换行输出print(val1)print(val2)# 不换行输出print(val1, end=" ")print(val2, end=" ")print()以上代码输出结果:
a
b
a b
标准输入
input 函数为标准流输出函数,参数为提示性的字符串,返回值为用户输入字符串,使用该语句会导致一个线程阻塞;
str_input = input("please input something: ") # 获取用户输入print("you input:" + str_input) # 打印用户输入input("Enter anything to exit")文件 IO
python 使用内置的 open() 函数创建文件对象,该函数的方法签名如下:
open(filename, mode [, buffering, encoding])- filename:指定文件路径名,支持绝对路径和相对路径;
- mode:文件读取模式;
- buffering:指定是否启动缓存区;
-
encoding:指定文件读写编码格式;
其中 mode 包括以下:
b:二进制模式;r:只读;r+:读写,不覆盖;w:只写;w+:读写,覆盖;a :追加模式
它们可以进行组合,这些打开模式可以参照下图:
文件写入
string = """Hello world!welcome to pythonthis is a test for file io"""# 1) 覆盖写入文件file = open("./test_file1.txt", "w+") # 打开文件,以读写覆盖模式打开file.write(string) # 向文件写入string file.close() # 关闭文件# 2)追加写入文件file = open("./test_file1.txt", "a+") # 打开文件,以读写追加模式打开file.write("This is the additional part")file.close()文件读取
# 打开文件,只读方式读取file = open("./test_file1.txt", "r")# 1)读取文件所有内容content = file.read() # 读取文件所有内容,并储存为一个string对象print(content)# orfile.seek(0, 0) # 重置文件读写指针lines = file.readlines() # 读取文的件每一行,以每一行为元素储存为一个 list 对象for line in lines: print(line, end="")print()# 2)读取文件中的一行file.seek(0, 0) # 重置文件读写指针line = file.readline() # 读取当前一行print(line)# 3)读取文件指定长度,在字符文件中指字符数,在二进制文件指字节数file.seek(0, 0)content = file.read(10) # 这里读取的是10个字符print(content)# 关闭文件file.close()文件读写指针行为控制
1)获取读写指针位置
file.tell() 函数用于获取当前文件读写指针位置,返回内容是从文件开头算起的字节数;
2)更改读写指针位置
file.seek(offset, from_what) 函数用于该变文件读写指针的位置
file.seek(offset, from_what) 函数用于该变文件读写指针的位置
-
from_what:0表示文件开头,1表示当前位置,2表示文件结尾
-
offset :基于 form_what 的偏移量;
- file.seek(x, 0):从起始位置偏移 x 个字节
- file.seek(x, 1):从当前位置偏移 x 个字节
- file.seek(-x, 2):从结尾位置向前偏移 x 个字节
解决非英文字符读写乱码
在默认情况下,file.open() 函数是以 ascii 读写文件的,假如以以上的方式读写中文等非英文字符,会导致字符乱码;
当导致字符乱码的因素是比较复杂的,这里有一种方式可以确保中文的正确的读写,即全程使用 UTF-8 或其他可容纳中文的编码格式进行;
首先确保 python 文件是以 utf-8 进行编码,可以在文件头以一下代码强制指定文件编码:
# -*- coding: utf-8 -*-之后以 utf-8 的编码格式打开文件就可以正常读写中文了,如下示例:
# 向文件写入中文file = open("./test_china.txt", "w+", encoding="utf-8")content = "白学家见一个打死一个。 ————鲁迅"file.write(content)file.close()# 向文件读取中文file = open("./test_china.txt", "r+", encoding="utf-8")content = file.read()print(content)file.close()对象序列化/反序列化
python 提供了 pickle 模块用于对象序列化/反序列化,使用示例如下:
import pickle# 待序列化的对象list_data = {"name": "assad", "city": ["Guangzhou", "Chaozhou"], "age": 20}# 序列化对象并写入文件file_output = open("./myList.dat", "wb")pickle.dump(list_data, file_output) # 将字典对象序列化后写入输出流file_output.close()# 从文件读取并反序列化为对象file_input = open("./myList.dat", "rb")read_data = pickle.load(file_input) # 从文件输入流中读取文并反序列化为字典对象print(read_data)file_input.close()# 输出:{'name': 'assad', 'city': ['Guangzhou', 'Chaozhou'], 'age': 20}