File Types: two major types of files that are stored on a computer File TypesText File
Binary File
Open()NOTE: Unless otherwise directed, the file location is in the same directory as the program being executed.
To process a file (read or write to a file), the file must first be opened. When opening a file a minimum of one parameter must be supplied. The name of the file, if the mode parameter is not supplied, the file will be opened in read only mode.
file name: this is the actual name of the file on the disk, including its file extension.
mode: the mode is how you are going to process the file.
CAUTION: binary files can be corrupted in a Windows environment, if the file is not opened as a binary file For binary files: For more detail, see python.org documentation file. file_object: the name that will be used in the program to process the file.
filename: a string that contains the name of the actual file on the disk
mode: a string that will be a 'r', 'w', 'a', 'b' or 'x'
open() ExampleThis will open the myData.txt file as f_input for reading: f_input = open('myData.txt', 'r') This will open the newData.txt file as f_output for writing: This will open the moreData.txt file as f_append for reading: close()When you open a file, it must also be closed. Closing a file after you are finished with it is the same for reading, writing or appending. close() Syntaxfile_object.close() file_object: the name that will be used in the program to process the file. close() ExampleThis will close the f_data file object: with()with is a multi-line statement. All statements that are indented after the with statement are part of the with statement. When opening a file using a with statement, the file is automatically closed when the block of code is complete. Therefore, there is no need to close the file after processing is complete. An error is not issued if the file is closed.
|
06.0 Python > Python Notes >