2018-05-03Python:文件处理

'''文件操作1.打开文件:用open函数,参数为文件路径和打开方式,打开文件返回为fileObject类型

2.读取文件:read函数来处理fileObject类型文件

3.open(path,'x') x = w 是写(原文覆盖),x = r 是读 x = a 写(原文后面追加)

4.换行写入:在要写入的字符串前加/n

5:读写特定编码的文章:open(path,'r',encoding='gbk/utf-8')

6:读写一行:readline() readlines() writelines()

7:工程中出现异常,和安全性考虑:with

'''

path ='C:/Users/HouYushan/Desktop/Text2.txt'

path1 ='C:/Users/HouYushan/Desktop/Text3.txt'

# 1

file =open(path,'a')

# 2 3

file.write('嘻嘻嘻嘻')

file =open(path,'r')

print(file.read())

file =open(path,'a')

# 4

print(file.write('\njjjjj'))

file =open(path1,'w')

str_list = ['hello\n','world\n','hello hhh\n']

# 6

new_file = file.writelines(str_list)

print('new_file:',new_file)

file =open(path1,'r')

print('file.read:',file.read())

file =open(path1,'r')

print('file.readlines:',file.readlines())

path2 ='C:/Users/HouYushan/Desktop/Text4.txt'

# 7

with open(path2,'w')as f:

print('write length:',f.write('hello world'))

你可能感兴趣的:(2018-05-03Python:文件处理)