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()

相关推荐