Home  >  Article  >  Backend Development  >  Python method to put each line in a file into an array as an array element

Python method to put each line in a file into an array as an array element

不言
不言Original
2018-05-02 16:14:041969browse

This article mainly introduces the method of python to put each line in the file into an array as an array element. It has a certain reference value. Now I share it with you. Friends in need can refer to it

Sometimes it is necessary to put the data in the file into an array. Here is a method to split the data according to the mark at the end of the file, and then put the split file into the array

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

Related recommendations:

Python implements the method of appending text to a specified line in txt

Python Method for outputting a two-dimensional array as a picture

The above is the detailed content of Python method to put each line in a file into an array as an array element. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn