JoomlaTemplates.me by HostMonster Reviews

How to read data from text file and set them as a variable in Python

Published: Friday, 06 July 2012

The original question was: how to read two columns from a text file into the editor and set them as variables, Pls help!!!!!!!

1) determine your working directory:
command: open('mydir.txt', 'wb').write(b'Hello')

A file mydir.txt will be created somewhere with contents "Hello". Look for the file, most probably in the directory where python is installed.

2) Once you have located the location of mydir.txt, you can place any other file you want to read from / write to in the same DIR or better still create a subdirectory for all your files.

example: I have Python installed in C:\Python27, so I created a sub-DIR with name "projects" under Python27 , and I can access it like this:

open('projects/mydir.txt', 'wb').write(b'Hello')

3) now that you know where you are working from, create a filename.txt there, ex: columndata.txt and fill the file with sample data - you can use excel.

to read the file, do:
>>> f = open("projects/columndata.txt", 'r')
>>> g = f.read()
>>> print g
21 3 10
34 13 41
56 8 98
88 45 63
99 9 128
10 34 256
23 0 4
90 0 8
22 20 4

Add comment


Security code
Refresh