Loading... # I/O流 ##1.更漂亮的输出格式 ### 使用str.format() 基本用法 ```python >>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!" ``` 花括号和其中的字符(称为格式字段)将替换为传递给 str.format() 方法的对象。 ```python >>> print('{0} and {1}'.format('spam', 'eggs')) spam and eggs >>> print('{1} and {0}'.format('spam', 'eggs')) eggs and spam ``` 如果在 str.format() 方法中使用关键字参数,则使用参数的名称引用它们的值。 ```python >>> print('This {food} is {adjective}.'.format( ... food='spam', adjective='absolutely horrible')) This spam is absolutely horrible. ``` ##2.读取键盘输入 ### raw_input函数 raw_input([prompt]) 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符) str = raw_input("请输入:") print("你输入的内容是: ", str) ### input函数 input([prompt]) 函数和 raw_input([prompt]) 函数基本类似,但是 input 可以接收一个Python表达式作为输入,并将运算结果返回。 str = input("请输入:") print("你输入的内容是: ", str) ---------------------------- 请输入:[x*5 for x in range(2,10,2)] 你输入的内容是: [10, 20, 30, 40] # 读写文件 ## 1.打开文件 ### open()函数 open() 返回一个 file object,最常用的有两个参数: open(filename, mode)。 f = open('workfile', 'w') 第一个参数是包含文件名的字符串。第二个参数是另一个字符串,其中包含一些描述文件使用方式的字符(默认为'r')。 mode可以是'r',表示文件只能读; 'w'表示只能写入(已存在的同名文件会自动被删除); 'a'表示打开文件以追加内容,任何写入的内容自动添加到文件末尾; 'r+'表示打开文件进行读写; ‘b’表示使用二进制模式; 'rb'表示以二进制格式打开一个文件用于只读,一般用于非文本如图片等; 'rb+表示以二进制格式打开一个文件用于读写; 'ab+'表示以二进制格式打开一个文件用于追加。 ### with关键词 一个好的习惯是使用**with**关键词处理文件对象。优点是文件在使用结束之后会自动关闭。 >>> with open('workfile') as f: ... read_data = f.read() >>> f.closed True 如果你没有使用with语句则应该在最后调用**f.close()**关闭文件对象。 ## 2.文件对象的方法 ### read()函数 **f.read()**读取整个文件的内容(如果你内存够的话)。如果到达文件尾了,**f.read()**将返回空字符串('')。 >>> f.read() 'This is the entire file.\n' >>> f.read() '' ### readline()函数 **f.readline()**从文件读取一行。如果**f.readline()**返回一个空的字符串**('')**,则表示已经到达了文件尾,而空行使用**'\n'**表示。 >>> f.readline() 'This is the first line of the file.\n' >>> f.readline() 'Second line of the file\n' >>> f.readline() '' 如果要从文件中读取行,你可以循环遍历文件对象。这是内存高效快速的,并简化代码。 with open(filename, 'r', encoding='utf-8') as f: for line in f: print(line, end='') 如果向以列表的形式读取文件中的所有行,可以使用**list(f)**或**f.readlines()**。 ### write()函数 **f.write(string)**会把string的内容写到文件中,并返回写入的字符数。 >>> f.write('This is a test\n') 15 在写入其它类型的对象之前,需要先把他们转换为字符串(文本模式)或者字节对象(二进制模式)。 **文本模式** value = ('the answer', 42) s = str(value) # convert the tuple to string f.write(s) **二进制模式** import struct list_dec = [1, 2, 3, 4, 53, 100, 220, 244, 255] with open('hexBin.bin', 'wb')as f: for x in list_dec: a = struct.pack('B', x) f.write(a) Last modification:January 20th, 2021 at 05:56 pm © 允许规范转载