[Tutor] Read, Write, Split and Append lines from a text file

Alan Gauld alan.gauld at btinternet.com
Sun Jul 20 10:16:40 CEST 2014


On 19/07/14 22:27, LN A-go-go wrote:

> AK 36
> AL 39
> AR 39
> AZ 45
> CA 61
> CO 54
>
> # and now my newbie attempt:
> # I can get this far in approach #1
>  >>> filename = "z:/Geog482/egund919/Program1/BOJ.txt"
>  >>> myfile = open(filename,"r")
>  >>> newfile = "z:/Geog482/egund919/Program1/BOJ_B.txt"
>  >>> mynewfile = open(newfile,"w")
>  >>> while True:
>   line = myfile.readline()
>   print line
>   mynewfile.write(line)
>   if not line: break


>
> States OJ
> AK 36

Assuming this is the output... where does the first
line come from?
Its not in your data above and you don't print it?
So either your data is not the real data or the code
is not the real code.
Either case makes it difficult for us to work out what is
really going on.

> UT 34
> VA 53
> VT 67
> WA 58
> WI 56
> WV 43
> WY 33

If this is the output what exactly is "wrong" with it?
Apart from the first line anomaly it looks exactly like
what I'd expect.

> In approach number 2: trying to append, convert to integer, but the list
> comes up empty:
>
>  >>> infile = open('C:/Python27/egund919/Program1/BOJ_B.txt','r')
>  >>> import string

Don't import string. Use the string methods instead.

>  >>> state_name = []
>  >>> data_value = []
>  >>> counter = 0
>  >>> x = 0
>  >>> line = infile.readline()
>  >>> while True:
>                line = infile.readline()
>                if not line: break

It would be easier to use enumerate and a for loop:

for counter, line in enumerate(infile):

>                counter = counter + 1
>                States, OJ = string.split(line)
>                XSTATES = str(States)
>                XNUM = int(OJ)

By convention all caps means a constant value. These obviously
change so it would be better to name them xstates and xnum.
Also since there is only one state per line it should be
xstate rather than xstates. Just minor style points.

>                state_name.append(XSTATES)
>                data_value.append(XNUM)

You could use a dictionary here instead of two lists.

states = dict()
for counter,line in ....
     ...
     states[xtstate] = xnum

>  >>> type(data_value)
> <type 'list'>
>  >>> print(data_value)
> []

This suggests your loop exited on the first iteration.
Is there a blank line at the start of the file?
This is another reason why using a for loop is better,
it wouldn't get caught out that way.


>  >>> print (line)
>
> All I get is errors from here on out.....

Tell us what the errors are. If they are actual Python
error messages then show us the full error message - it
is full of useful data. If they are just errors in the
sense that they are not what you expected, then tell us
what you expected and show us what you got.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list