python文件读写

"""
open函数:
语法:open(filename,mode=‘r’,buffering=-1,…)
mode可选参数,默认值为r。
文件的打开模式如下几种
'r': 只读模式。默认模式,如果文件不存在,会引发异常。
'w': 写模式。如果文件不存在,则创建文件。如果文件已存在,则清空文件并写入新内容。
'a': 追加模式。如果文件不存在,则创建文件。如果文件已存在,则将新内容添加到文件末尾。
buffering也可选参数,默认值为-1(0代表不缓冲,1或者大于1的值表示缓冲一行或指定缓冲区大小)
返回值:
open()函数返回一个文件(file)对象
文件对象可迭代
有关闭和读写文件的相关函数/方法
"""

"""
# 方法二:使用with关键字写法
with open("文件地址","读写模式") as 变量名:
全部读取出来
"""
#1、、打开文件模式r w a
#read
with open(r'D:\\Duments\\testfile\test1.txt','r',encoding='utf-8') as file_name:
    file_read=file_name.read()#全部读取出来
print(file_read)
print('1*'*20)
#readlines() 会从txt文件取得一个列表,列表中的每个字符串就是scores.txt中的每一行。而且每个字符串后面还有换行的\n符号
"""
想要去除\n使用strip()
strip()方法删除多余空格和特殊字符:制表符(\t)、回车符(\r)、换行符(\n)等
str.strip():删除字符串前后(左右两侧)的空格或特殊字符。默认是换行符号,strip('\n')
str.lstrip():删除字符串前面(左边)的空格或特殊字符。lest
str.rstrip():删除字符串后面(右边)的空格或特殊字符。right
str还有用replace()函数去掉所有空格string = " * it is blank space test * "str_new = string.replace(" ", "")print str_new
"""
with open(r'D:\\Duments\\testfile\test1.txt','r',encoding='utf-8') as file_name:
    file_read1=file_name.readlines()
    file_read2=[file_read1.strip() for file_read1 in file_read1]#这里使用了列表推导式
print(file_read2)
print('2*'*20)

#readline读取一行
with open(r'D:\\Duments\\testfile\test1.txt','r',encoding='utf-8') as file_name:
    file_read1=file_name.readline()
print(file_read1)
print('*'*20)

#写入
#write如果打开文件模式中包含 w(写入),那么向文件中写入内容时,会先清空原文件中的内容,然后再写入新的内容
with open(r'D:\\Duments\\testfile\test2.txt','w',encoding='utf-8') as file_name1:
    file_name1.write('我是高手')
"""
writelines() 方法是用于将字符串列表写入文件的方法。但是需要注意以下几点: 

writelines() 方法只接受字符串列表作为参数。如果要写入单个字符串,请使用 write() 方法。
writelines() 方法不会在字符串之间自动添加换行符,需要手动将其添加到字符串中。
writelines() 方法不会在列表的最后添加空行,如果需要在最后一行添加空行,请手动添加一个包含换行符的空字符串。
在使用 writelines() 方法时,需要保证传递的参数是一个字符串列表。如果参数是一个生成器对象,需要将其转换为列表再传递。
python将list列表元素写入文件自动换行的三种方式
with open(cls_path,'w') as f1:
            #方法一:
        for line in cls_labelList:
            f1.write(line+'\n')
            #方法二:
#             lists=[line+"\n" for line in lists]
#            f1.writelines(lists)
            #方法三:
#             f1.write('\n'.join(lists))
"""
#file_read2
with open(r'D:\\Duments\\testfile\test3.txt','w',encoding='utf-8') as file_name2:
    file_name2.writelines(file_read)
with open(r'D:\\Duments\\testfile\test3.txt','r',encoding='utf-8') as file_name3:
   fils= file_name3.read()
print(fils)


#seek 移动光标和指针
"""
参数
Syntax: f.seek(offset, whence),f指的是file(或$你的文件名)
Parameters:
offset: 将光标向前移动n个位置
whence: 参考位置,一般参数为0,1,2
0 :将开头作为参考位置
1 :将当前作为参考位置
2 :将末尾作为参考位置
"""

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

詹姆斯_杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值