python从txt文件中读取数字,并放入list中 用Python读取文件中的数字并加入list的问题
python \u4ecetxt\u4e2d\u8bfb\u53d6\u6570\u636e\u5230 list \u4e2dlist1,list2,list3.... \u6709\u591a\u5c11\u884c\u4e8b\u5148\u77e5\u9053\uff1f
a = open('myfile.txt')lines = a.readlines()lists = []#\u76f4\u63a5\u7528\u4e00\u4e2a\u6570\u7ec4\u5b58\u8d77\u6765\u5c31\u597d\u4e86for line in lines: lists.append(line.split())print(lists)
array = []for line in open('testdata.txt'): array.extend(line.strip().split(' '))array = map(int, array)print(array)
背景:
文件内容每一行是由N个单一数字组成的,每个数字之间由制表符区分,比如:
0 4 3 1 2
2 1 0 3
1 2 0
……
现在需要将每一行数据存为一个list,然后所有行组成一个大的list。
工具:
1.strip():用于移除字符串头尾指定的字符,默认为空格,返回是字符串。
2.split():通过指定分隔符对字符串进行切片,返回是字符串组成的list。
实例:
绛旓細濡備綍璁python鎶浠巘xt鏂囦欢涓鍏鐨勬枃瀛楁寜20涓瓧绗︿竴琛岀殑褰㈠紡鍒嗛殧寮鍛傚ぇ姒傜殑鎬濊矾鏄紝鍏璇诲叆鏂囦欢鎵鏈夊瓧绗︼紝鐒跺悗浣跨敤range鐢熸垚[0,20,40,...]鐨勫垪琛ㄤ互渚涚储寮曪紝鐒跺悗鐢ㄨ繖涓储寮曪紝鐢熸垚鏈夊叧浜庤瀛楃涓茬殑鏂板垪琛╗s[0:20],s[20:40],...]锛岃嫢涓嶄笓闂ㄥ幓闄ゆ崲琛岀锛屼唬鐮佺敤杩欎釜鎬濊矾灏卞浜嗭紝鍙互杩欎箞鍐欙紙浠ヤ笅13...
绛旓細1 瀹夎xlrd妯″潡 pip install xlrd2 璇诲彇Excel -*- coding: utf-8 -*- import xlrdimport os,shutildef open_excel(file= 'file.xls'): try: data = xlrd.open_workbook(file) return data except Exception,e: print str(e) def mycopyfile(srcfile,dstfile): if no...
绛旓細浣跨敤鈥滄鍒欒〃杈惧紡鈥濇渶鏂逛究銆傚彲浠ュ厛鏌ユ壘璧勬枡棰勫厛瀛︿範涓涓嬨傚鏋滀笉鐢ㄦ鍒欒〃杈惧紡锛屽氨鍙兘浣跨敤瀛楃涓叉煡鎵剧殑鏂瑰紡銆傚厛鏌ユ壘鈥滃笇鏈涒濆湪鍝噷锛岀劧鍚庡啀鎴彇銆俧= open('filename.txt','r')findtxt = '甯屾湜'lnfindtxt = len(findtxt)txt = f.readlines()txt = str(txt)pos1 = txt.find(findtxt)pos2 = ...
绛旓細python鐢ㄦ硶闈炲父绠鍗曘備唬鐮佸涓:import math f=open("1.txt")s=f.read()nums=s.split(" ")sum=0 count=len(nums)min=-99999999 for num in nums:sum=sum+int(num)avg=math.floor(sum/count)nums.sort(key=int)result=''f=open("2.txt","w")reault=result+' ...
绛旓細filename: test.py import os users = [] # 鐢ㄦ潵淇濆瓨浠庢枃浠朵腑璇诲彇鐨勬暟鎹 for item in os.listdir('.'): # 閬嶅巻鎸囧畾鐩綍 if os.path.isfile(item) and item.endswith('.txt'): # 鍒ゆ柇鏄惁涓.txt鏂囦欢 f = open(item) # 鎵撳紑鏂囦欢 for line in f: # 璇诲叆鏂囦欢鐨勬瘡涓琛 if line.starts...
绛旓細coding: UTF-8blist = []split_char = ' 'with open('b.txt', 'r') as bf: blist = [b.strip().split(split_char) for b in bf]word = '鎴'print repr(word)for bl in blist: print bl if word in bl: print 'blist[%d][%d]' % (blist.index(bl),bl.in...
绛旓細python3.x result=[]with open('a.txt','r') as f:for line in f:result.append(list(map(float,line.split(',')))print(result)python2.7 result=[]with open('a.txt','r') as f:for line in f:result.append(map(float,line.split(',')))print(result)...
绛旓細鑳屾櫙锛鏂囦欢鍐呭姣忎竴琛屾槸鐢盢涓崟涓鏁板瓧缁勬垚鐨勶紝姣忎釜鏁板瓧涔嬮棿鐢卞埗琛ㄧ鍖哄垎锛屾瘮濡傦細0 4 3 1 2 2 1 0 3 1 2 0 鈥︹︾幇鍦ㄩ渶瑕佸皢姣忎竴琛屾暟鎹瓨涓轰竴涓猯ist锛岀劧鍚庢墍鏈夎缁勬垚涓涓ぇ鐨刲ist銆傚伐鍏凤細1.strip()锛氱敤浜庣Щ闄ゅ瓧绗︿覆澶村熬鎸囧畾鐨勫瓧绗︼紝榛樿涓虹┖鏍硷紝杩斿洖鏄瓧绗︿覆銆2.spl...
绛旓細): linea=linea.replace("\n","").split("\t") fp-1.writeline(linea[0]) fp-2.writeline(linea[1])fpa.close()fp-1.close()fp-2.close()棣栧厛鎵撳紑鏁版嵁瀛樻斁鐨鏂囦欢杩涜锛岃鎿嶄綔锛涚劧鍚庢墦寮涓や釜鍐欐枃浠讹紝濡傛灉涓嶅瓨鍦紝鍙互鐩存帴鍒涘缓锛涙寜琛璇诲彇锛岀劧鍚庡垎鍓诧紝鍒嗗埆鍐欏叆涓嶅悓鐨勬枃浠躲
绛旓細f = open("foo.txt") 锛# 杩斿洖涓涓鏂囦欢瀵硅薄銆俵ine = f.readline()锛#璋冪敤鏂囦欢鐨 readline()鏂规硶銆倃hile line锛歱rint line, #鍚庨潰璺 ',' 灏嗗拷鐣ユ崲琛岀锛# print(line, end = '')銆# 鍦 Python 3涓娇鐢紝line = f.readline()锛宖.close()銆傜敤閫斿箍娉涳細閫熷害蹇細Python 鐨搴曞眰鏄敤 C ...