python-open/with打开文件
open方法
file = open(filename [,mode,encoding])
file.close()
| mode | 解释 |
|---|---|
| w | 以只写模式打开文件,文件指针在开头 |
| r | 以只读模式打开文件,文件指针在开头 |
| a | 以追加模式打开文件,在文件末尾追加内容 |
| b | 以二进制方式打开文件,不能单独使用,需要与其他模式一起使用,如rb,wb |
| + | 以读写方式打开文件,不能个单独使用,需要与其他模式一起使用,w+ |
file = open(r'D:\Users\Desktop\新建文本文档.txt','r')
print(file.read()) # 读取所有内容
print('\n')
file.close()
with方法
with open(r'D:\Users\Desktop\新建文本文档1.txt','w') as file:
file.write('奋斗成就更好的自己')
通过python往已有数据中插入新的一行
以csv和text文件为例:
"""在csv文件中第一行添加索引字段"""
filename = r'D:\Users\Desktop\data-test.csv'
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
#mid, text, source, uid
text = 'mid' + ',' + 'text' + ',' + 'source' + ',' + 'uid'
f.write(text + '\n' + content)