FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

Python - Using files




As I have discussed in my previous couple of blogs, the whole using files thing is new, until now I have just used IDLE to write my basic programs.

I am using this post to discuss the new commands I can use to manipulate .txt files through Python.



open obviously opens the file. At this stage, it appears the best way to use this command is to assign a variable, such as:
variable = open(thefilevariable)

There is a second argument you can put, which relates to what you want to do with the file.

close is apparently a good idea after you finish with the file you have opened, saves your work...
Syntax:
variable.close()

read will display all the text in the txt file. There is no need to add the second argument to the open command.
Syntax:
print variable.read()

readline reads only the first line, or one line starting at where seek is if used.
Syntax:
print variable.readline()

truncate empties the file. Appears to not be required if using 'write'.
Syntax:
variable.truncate()

write OVERWRITES the file. Note that in order to do this, you MUST add the argument "w" to the open statement.
Syntax of open:
variable = open(thefilevariable, "w")
Syntax of write:
variable.write("string you want in file or variable whose data you want in file")

"a" (append I think) adds extra data to the end of the file. Note in the open statement...
Syntax of open:
variable = open(thefilevariable, "a")
variable.write("string you want in file or variable whose data you want in file")

seek appears to find the character number in the data in the file. i haven't played much with this yet to confirm.
Syntax:
variable.seek(int)

exists is a boolean which checks whether or not the file in question exists. MUST import os.path to use.
Syntax:
exists(filevariable)
noting that it can be used where you would use a boolean.

DISCLAIMER: That as I am new to these commands, it is probable, even definate, that these could be used in a more superior way, I may even have some errors in meaning or understanding... This disclaimer applies for all my IT posts...

Feel free to correct, comment, or ask...



0 blog comments below




FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.