Python Programming/Files
From Wikibooks, the open-content textbooks collection
[edit] File I/O
Read entire file:
inputFileText = open("testit.txt", "r").read() print inputFileText
Read certain amount of bytes from a file:
inputFileText = open("testit.txt", "r").read(123) print inputFileText
Read one line at a time:
for line in open("testit.txt", "r").readlines(): print line
Write to a file:
outputFileText = "Here's some text to save in a file" open("testit.txt", "w").write(outputFileText)
Append to a file:
outputFileText = "Here's some text to add to the existing file." open("testit.txt", "a").write(outputFileText)
Note that this does not add a line break between the existing file content and the string to be added.
[edit] Testing Files
Determine whether path exists:
import os os.path.exists('<path string>')
When working on systems such as Microsoft Windows(tm), the directory separators will conflict with the path string. To get around this, do the following:
import os os.path.exists('C:\\windows\\example\\path')
A better way however is to use "raw", or r:
import os os.path.exists(r'C:\windows\example\path')
[edit] Common File Operations
To copy or move a file, use the shutil library.
import shutil shutil.move("originallocation.txt","newlocation.txt") shutil.copy("original.txt","copy.txt")
| Previous: Modules and how to use them | Index | Next: Text |

