MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Python & Perl: File Reading & Writing

Xah Lee, ,

Python

To open a file and write to file do:

f=open('xfile.txt','w')

This creates a file “object”, and we named it “f”.

The second argument of “open” can be 'w' for write (overwrite exsiting file), 'a' for append, 'r' for read only.

To actually print to or read from file, use the file object's methods.

Reading entire file:

text = f.read()

Reading one line at a time:

line = f.readline()

Reading entire file as a list, of lines:

mylist = f.readlines()

To write to file, do:

f.write('yay, first line!\n')

When you are done, close the file:

f.close()

Closing files saves memory while the program is still running. You should always do that.

Here is a complete example of reading in a file and writing it to another file.

# -*- coding: utf-8 -*-
# python

f=open("/Users/xah/t.txt",'r')
f2=open("/Users/xah/t2.txt",'w')
for line in f:
    f2.write(line)
f.close()
f2.close()

Perl

Here is a example of reading in a file and print it out:

# -*- coding: utf-8 -*-
# perl

open(f,"<x.pl") or die "error: $!";
while ($line = <f>) {print $line}
close(f) or die "error: $!";
print "am printing myself\n";

The f in the above code is called a “file handle”. It is sometimes capitalized (⁖ open(F,"<x.pl")), and can also be a string instead (⁖ open("f","<x.pl") ).

The < in "<x.pl" means reading a while. To open a file for writing, use >.

The <f> reads in a line from the file handle “f”.

In the line close(f) or die "error: $!";, it essentially means if (not close) then abort with error message. The die is abort, the $! is a predefined variable that holds system errors.

Here is a complete example of reading in a file and writing it to another file.

# -*- coding: utf-8 -*-
# perl

open(f,"</Users/xah/t.txt") or die "error opening file f: $!";
open(f2,">/Users/xah/t2.txt") or die "error opening file f2: $!";
while ($line = <f>) {print f2 $line;}
close(f) or die "error: $!";
close(f2) or die "error: $!";
blog comments powered by Disqus