python 把文件中的每一行以数组的元素放入数组中的方法
有时候需要把文件中的数据放入到数组中,这里提供了一种方法,可以根据文件结尾的标记进行数据拆分,然后再把拆分的文件放入数组中
#-*-coding:utf-8-*-
f=open("username.txt","w")
f.write("Lycoridiata\n")
f.write("wulei\n")
f.write("leilei\n")
f.write("Xingyu\n")
#两种方法实现把每一行文件以数组元素的形式放进数组中(split/splilines)
其中spit是一个分割的作用,以'\n'为分割点,即把每一段分割成一个元素放入数组中
f=open("username.txt","r")
#print(f.read())
get=f.read()
result=get.split('\n')
#直接用splitlines()放法来实现行分割
other_result=get.splitlines()
foriinrange(len(other_result)):
print(result[i])
print("******")
print(other_result[i])
print("******")
f.close()
#直接以‘,'为分割点
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
ff=open("newfile.txt","w")
ff.write("askhdas,lfaskj,fhashfk,lhaskl,fhlaskhf,lasyhlfhnal,sfnklak,sl,fhla,skhflashfk,lhasklfha,slfhlakshf")
ff=open("newfile.txt","r")
get=ff.read()
result=get.split(",")
forkinrange(len(result)):
print(result[k])
print("$$$$$$$$$")
ff.close()
以上这篇python把文件中的每一行以数组的元素放入数组中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短