python 把文件中的每一行以数组的元素放入数组中的方法

yipeiwu_com6年前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()

以上这篇python 把文件中的每一行以数组的元素放入数组中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python科学计算包numpy用法实例详解

本文实例讲述了Python科学计算包numpy用法。分享给大家供大家参考,具体如下: 1 数据结构 numpy使用一种称为ndarray的类似Matlab的矩阵式数据结构管理数据,比py...

Python实现扩展内置类型的方法分析

本文实例讲述了Python实现扩展内置类型的方法。分享给大家供大家参考,具体如下: 简介 除了实现新的类型的对象方式外,有时我们也可以通过扩展Python内置类型,从而支持其它类型的数据...

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法

今天在网上copy的一段代码,代码很简单,每行看起来该缩进的都缩进了,运行的时候出现了如下错误:  【解决过程】  1.对于此错误,最常见的原因是,的确没有缩进。...

用python实现对比两张图片的不同

用python实现对比两张图片的不同

from PIL import Image from PIL import ImageChops def compare_images(path_one, path_two,...

python基于pygame实现响应游戏中事件的方法(附源码)

python基于pygame实现响应游戏中事件的方法(附源码)

本文实例讲述了python基于pygame实现响应游戏中事件的方法。分享给大家供大家参考,具体如下: 先看一下我做的demo效果: 当玩家按下键盘上的:上,下,左,右键的时候,后台会打...