Python 3.6
file1 = open('abc.txt', 'r')print(file1.name)file1.close()直接用open,定义只读模式,可以查看文件的名字,记得要关闭文件。
file1 = open('abc.txt')print(file1.mode)file1.close()默认的是只读模式,用mode可以查看。
with open('abc.txt', 'r') as file1: print(file1.name) 如果用with open就不用加上close关闭文件
with open('abc.txt', 'r') as file1: print(file1.name) print(file1.closed)用closed验证一下是否已经关闭了文件。
with open('abc.txt', 'r') as file1: print(file1.name) print(file1.read())关闭了的文件就不能直接读取了。
with open('abc.txt', 'r') as file1: txt = file1.read() print(txt) 我们可以把读取的内容保存到变量并且打印出来。
with open('abc.txt', 'r') as file1: txt = file1.readlines() print(txt) readlines是把所有的以行数来读取。
with open('abc.txt', 'r') as file1: txt = file1.readline() print(txt, end='') txt = file1.readline() print(txt, end='') readline则是只读取一行。
with open('abc.txt', 'r') as file1: txt = file1.read(3) print(txt, end='@') txt = file1.read(3) print(txt, end='@') 我们可以用read来定义每次读取多少个字符。
with open('abc.txt', 'r') as file1: txt = file1.read(3) print(txt) txt = file1.read(3) print(txt) print(file1.tell()) 用tell可以查看当前阅读的指针位置。
with open('abc.txt', 'r') as file1: txt = file1.read(3) print(txt) file1.seek(0) txt = file1.read(3) print(txt) 用seek可以让指针到指定的位置,比如0就是从头来。
with open('abc.txt', 'r') as file1: with open('aaa.txt', 'w') as file2: for i in file1: file2.write(i) 用这个嵌套可以把一个文件的内容复制到另外一个文件里。
注意模式r和w的区别