by
0
7
303k
31
Top 1% !
Popular
Pearl of Wisdom
Tagged
Easy-to-find
Specified
OpenSource
Popularity: 3655th place
Created
Modified Sep 10, 2013

Published on:

Architecturex86_64
LanguagePython
LicenseMIT_X11

How to read and parse a txt file in python

This code shows how to read a txt file and parse the data
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11175/How-to-read-and-parse-a-txt-file-in-pyth?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import os import sys myfile = open('/some/path/to/file.txt', "r") # EXAMPLE OF FILE FORMAT: # abc 123 234 456 678 # def 122223 2333334 454446 611178 # ghi 144423 211134 44456 61114478 for line in myfile.readlines(): name= '' numList = list() print line try: name = line.split()[0] # it will get 'abc'/'def'/'ghi' numList = line.split()[1:] # it will get all other stuff inline... except: print "Invalid file format" myfile.close() sys.exit(1) if not numList: print("Invalid numList format! name= " + str(name)) myfile.close() sys.exit(1) print 'name='+str(name) print 'numList='+str(numList) myfile.close()
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus