f1 = open(r'E:PythonDatadata1.txt') #读取data1.txt文件,使用系统默认缓冲区大小, 为了读取快点,使用缓存吧!
f = open(r'E:PythonDatadata2.txt', 'w') f.write('Hello World !') f.close() f = open(r'E:PythonDatadata2.txt', 'r') p1 = f.read(5) # 先读5个字节 p2 = f.read() # 余下的都读出来 f.close()
file_obj.readlines(), file_obj.readline(), file_obj.writelines()
f = open(r'E:PythonDatadata3.txt') cNames = f.readlines() #把数据从文件一行行读取,返回一个列表 print(cNames) f.close()
#结果, readlines()读取的结果中,不去掉换行符
['GOOGLE Inc
', 'Nicrosoft Corporation
', 'Apple Inc.
', 'Facebook, Inc.']
# Filename:revcopy.py f1 = open(r'E:PythonDatadata3.txt') # 读 cNames = f1.readlines() for i in range(0, len(cNames)): cNames[i] = str(i+1) + '.' + cNames[i] f1.close() f2 = open(r'E:PythonDatadata3_out.txt', 'w') # 写 f2.writelines(cNames) f2.close()
s = 'Tencent Technology Company Limited' f = open(r'E:PythonDatadata3.txt', 'a+') f.writelines(' ') f.writelines(s) f.seek(0, 0) # 把文件指针移到文件首部 cNames = f.readlines() print(cNames) f.close()