[Tutor] Files and file attributes
Remco Gerlich
scarblac@pino.selwerd.nl
Thu, 22 Feb 2001 00:20:32 +0100
On Wed, Feb 21, 2001 at 05:55:11PM -0500, Pat/Bob Fisher wrote:
> I am pretty new at programming in Python, but have had experience in
> programming in other languages. I went through the tutorial which I thought
> was fairly good, except the section on the methods of file objects was
> pretty sparse. It seems to me that dealing with files is rather awkward. I
> have used the list representation filelist = f.readlines() and then used the
> fine list methods to manipulate the filelist, but I am having trouble
> getting a new file from my new filelist.
Wait! I don't understand that. What 'filelist = f.readlines()' does, is read
the whole file f, turn it into a line by line list, and assign it to
filelist. What do you mean, getting a new file from a list of lines?
> The g.write('string') gives me a whole lot of extraneous stuff.
It should write the string 'string' to file g and nothing else. Can you
describe what you're seeing?
> Another problem I am having is trying to open files in other directories. For example,
>
> f=open('C:\tmp\testfile','r+') just doesn't work for me.
A \ inside a string has a special meaning, so that filename isn't what you
think it is. Use one of these three options:
1. Forward slashes. f=open('C:/tmp/testfile','r+'). Yes, that works!
2. 'Raw' strings. f=open(r'C:\tmp\testfile','r+'). The r before the string
means that the backslashes are to be left in the string.
3. Escape the backslashes. f=open('C:\\tmp\\testfile','r+').
> Can anyone help, or at least tell me where I can learn more about file manipulation?
It's really pretty simple. For instance, if you want to read file 'a',
add a space to each line, and write the lot to file 'b', you could do:
a = open('a','r')
b = open('b','w')
for line in a.readlines():
b.write(" "+line)
a.close()
b.close()
Please try to explain what goes wrong exactly.
--
Remco Gerlich