1读取文件;2仅仅写;3同时读写

file_path='D:/1/1.txt'
with open(file_path) as file1:
    print(file1.read())
'''
ffqqss
'''

 

file_path='D:/1/1.txt'
# 1.read 返回字符串
with open(file_path) as file1:
    print(file1.read())
'''
name:fqs
age:18
hobby:game
'''
# 2.readline 返回字符串
with open(file_path) as file2:
    print(file2.readline())
'''
name:fqs
'''
3.readline 返回列表 包含换行符\n
with open(file_path) as file3:
    print(file3.readlines())
'''
['name:fqs\n', 'age:18\n', 'hobby:game']
'''

 4.read().splitlines() 返回列表 没有换行符\n
file_path = '1.txt'
with open(file_path,'r') as file3:
    print(file3.read().splitlines())
file3.close()
'''
 ['name:fqs', 'age:18', 'hobby:game']
'''
# 5追加写入


with open(file_path,'a') as f:
      print(f.write('追加内容,世界充满未知'))
f.close()

# 6 清空写入

with open(file_path,'w') as f:
    print(f.write('123'))

 

file_path='2.txt'
# 1清空添加  file_path 不存在 新建
with open(file_path,'w+') as f:
      f.write('追加内容,世界充满未知')
      f.seek(0)#更改处理时指针所在位置
      print(f.read())
f.close()
# 2追加  file_path 不存在 新建
with open(file_path,'a+') as f:
      f.write('追加内容,世界充满未知')
      f.seek(0)#更改处理时指针所在位置
      print(f.read())
f.close()
# 3覆盖  file_path 不存在 报错
with open(file_path,'r+') as f:
      f.write('1追加内容,世界充满未知')
      f.seek(0)#更改处理时指针所在位置
      print(f.read())
f.close()

 

posted @ 2023-07-10 15:27  胖豆芽  阅读(6)  评论(0编辑  收藏  举报