python进行文件读写

python进行文件读写

1. 打开文件的两种方式

方法一

f = open('data.txt','r') # 获得文件对象
f.close() # 关闭文件

方法二

with open('data.txt','r') as f:
	str = f.read() # 对文件的操作

2. 读文件

2.1 将文件读入到一行字符串中

str = f.read()

2.2 按行读取文件

lines = f.readlines()
for line in lines:

2.3 将文件读入到数组中

import numpy as np
data = np.loadtxt('data.txt')

3. 写文件

3.1 将字符串写入文件

with open('data.txt','w') as f:
    f.write(line)

3.2 列表写入文件

data = ['a','b','c']
with open("data.txt","w") as f:
    f.writelines(data)

3.3 数组写入文件

import numpy as np
np.savetxt('data.txt',data) # 或 np.save('data.txt',data)
---- suffer now and live the rest of your life as a champion ----
原文地址:https://www.cnblogs.com/popodynasty/p/14476615.html