2005-01-21
To open a file and write to file do:
f=open('xfile.txt','w')
this creates a file “object” and named it f.
The second argument of open can be “'w'” for write (overwrite exsiting file), “'a'” for append, “'r'” or read only.
To actually print to or read from file, use the file object's methods. Example:
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 and is proper in large programs.
Here is a complete example of reading in a file and writing it to another file. (essentially copying)
# 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()
Reference: Python Doc↗.
Reference: Python Doc↗.
Here is a example of reading in a file and print it out:
# 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 (e.g. “open(F,"<x.pl")”), and can also be a string instead (e.g. “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. (essentially copying)
# 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: $!";
Reference: perldoc -f open↗.
Reference: perldoc -f die↗.
Page created: 2005-01. © 2005 by Xah Lee.