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() for i in range (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(",") for k in range(len(result)): print(result[k]) print("$$$$$$$$$") ff.close()
相关推荐
CodeAsWind 2020-08-17
sunnyhappy0 2020-07-09
cxcxrs 2020-06-26
深思千年 2020-06-10
xmwang0 2020-06-01
fgleeldq 2020-05-27
ShiShuo 2020-05-16
文山羊 2020-05-08
tengyuan 2020-05-07
Leewoxinyiran 2020-05-06
sschencn 2020-05-04
vevoly 2020-05-04
一只码畜 2020-04-22
sulindong0 2020-03-09
GoatSucker 2020-02-24
sdwylry 2020-02-14