[Tutor] using python for parsing

Steven D'Aprano steve at pearwood.info
Thu Jun 27 02:46:22 CEST 2013


On 27/06/13 03:05, Makarand Datar wrote:
> Hi,
>
> I know practically nothing about python. I know how to install it and all
> that kind of stuff. I want to use python for parsing a text file. The task
> is to read in a text file, and write out another text file that is written
> in some particular way using the data from the file that was read in. The
> question is how do I go about this? What part of python documentation, or a
> book I should read etc. I dont want to start reading a python book from the
> first page. I just want to do this parsing task and I will learn about
> whatever I need to as I encounter it.


That depends on what you mean by "written in some particular way". It also depends on what version of Python, and what operating system. (I assume Windows, since Python is nearly always pre-installed on Linux.)

The simplest, most basic way is to do this is something like this:

filename = "C:/path/to/some/file.txt"
f = open(filename, 'r')
for line in f:
     print(line)

f.close()



In more recent versions, this is perhaps better written as:

filename = "C:/path/to/some/file.txt"
with open(filename, 'r') as f:
     for line in f:
         print(line)



Don't forget that indentation is significant.

Instead of print(line), a more realistic example would parse the line in some way, and that depends on the "particular way" you mention above. For example, given some line, I might split it into words, then print the first word, the second word, and the last letter of the third word:


words = line.split()
print(words[0], words[1], words[2][-1])



-- 
Steven


More information about the Tutor mailing list