[Tutor] Read, Write, Split and Append lines from a text file
Danny Yoo
dyoo at hashcollision.org
Sun Jul 20 03:57:01 CEST 2014
On Sat, Jul 19, 2014 at 2:27 PM, LN A-go-go
<lnartist at yahoo.com.dmarc.invalid> wrote:
>
>
> I have given it all I got: a week trying to open, read, write, split, append, convert to integers and then manipulate the data. I have attached the file I want to pull the names and numbers from. I'll cut and paste it incase that doesn't work and then include a sample of the python shell code.
>
[cut]
Sounds good so far.
> # 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
After you have written all these lines to 'newfile', did you call
close() on "newfile"? I was expecting:
mynewfile.close()
at the end of this block; the fact that it's missing looks unusual to me.
It may matter. File buffering may prevent another read of the file
from seeing the output you've written until the file has been
committed to disk.
> In approach number 2: trying to append, convert to integer, but the list comes up empty:
Given the logic of the block, there are a few ways that the data_value
may be empty. Let's take a look at it again.
infile = open('C:/Python27/egund919/Program1/BOJ_B.txt','r')
# ...
data_value = []
# ...
while True:
line = infile.readline()
if not line: break
# some content cut
data_value.append(...)
I've omitted all but what I think is essential for analyzing this
problem. I believe that the only way that data_value can be empty,
given the control flow of this program, if is the infile.readline()
returns a false value. The suggestion above about making sure the
file has been committed to disk is meant to address this possibility.
By the way, the looping over the file, using readline(), is
stylistically unusual. Files are "iterable": they can be used in for
loops directly. That is, the block:
infile = open('C:/Python27/egund919/Program1/BOJ_B.txt','r')
while True:
line = infile.readline()
...
can be written as:
infile = open('C:/Python27/egund919/Program1/BOJ_B.txt','r')
for line in infile:
...
and in general, this is preferable to the explicit readline() approach
you're using to iterate over the lines of a file.
More information about the Tutor
mailing list