文件读写/字符串方法

一、文件读写:

f = open('file.txt',encoding='utf-8')    #打开文件
print(f.read())     #读取文件全部内容
print(f.readline())    #读取文件第一行
print(f.readlines())  #读取文件,把文件的每一行放到一个list中
r+读写模式
w+写读模式
a+追加读写
f = open('file.txt','a+')
f.seek(0) #文件指针放在0的位置,只对读有用
f.truncate() #清空文件内容
print(f.tell())    #查看指针位置
f.write('hahaha') #会清空原有内容
names = ['a','b','c']
st = ('qw,wq')
f.write(names)
f.writelines(st)
f.close()

高效处理文件方法
循环文件中的每一行
fw = open('filename.txt')
count =1
for f in fw:
f = f.strip()
stu_list = f.split(',')
print (stu_list)
count+=1

二、字符串方法(不可变)

name = 'f best  test  '
print (name.strip())   #新name默认去掉首尾空格和换行符
print (name.lstrip())   #删左边
print (name.rstrip())   #删右边
print (name.count('e'))   #查找e出现的次数
print (name.capitalize()) #首字母大写
print (name.center(50,'-')) #前后加-
print (name.find('f'))    #找到字符串f,返回下标,不存在返回-1
print (name.index('f'))   #找不到f报错
print (name.upper())    #所有小写字母变大写
print (name.lower()) #大写变小写
file_name = 'a.txt'
print (file_name.endswith('.txt')) #判断字符串以什么结尾
print (file_name.startswith('a')) #判断已什么开头
print (name.replace('te','be')) #新name默认去掉首尾空格和换行符
print ('123a'.isdigit()) #是否全是数字
print (name)

1、分隔符:

st = 'a,b,c,d'
print(st.split(' ')) #字符串分割,默认按照空格分割st = 'a b c d'

2、连接

list = ['a','b','c']
res = ','.join(list)
#用逗号把字符串连接起来
print(res)
原文地址:https://www.cnblogs.com/wang-hao-yue/p/8178031.html