150 likes | 424 Views
Files in Python. The Basics. Why use Files?. Very small amounts of data – just hardcode them into the program A few pieces of data – ask the user to input them More than this, you need an external file stored on secondary storage. External data files. Handles large amounts of data
E N D
Files in Python The Basics
Why use Files? • Very small amounts of data – just hardcode them into the program • A few pieces of data – ask the user to input them • More than this, you need an external file stored on secondary storage
External data files • Handles large amounts of data • Data is independent of program, so program can change without changing data • Easier to edit data in an editor, instead of during run of program (can’t go back!) • Use the same data for input to different programs • Output files can be saved for later use • Output of one program can be used for input of another
Text files versus Binary files • Text files created by editors, stored as ASCII codes • Binary files stored as raw binary numbers, have to be handled differently • Text files are manipulated sequentially only • Binary files can be manipulated sequentially or randomly (we will not do binary files in this class)
Creating a text data file • This is done just like creating any other text file • You can use Notepad • You can use the editors of the IDEs that create Python • You can use a word processor like Word if you are careful to save as plain text • Store the text file in the same folder as you put your source code
Delimiters • The \n (newline) (carriage return) is a very important symbol in text files. • It delimits what Python calls a ‘line’ in the file. • It gets put into the file whenever you press Enter at the end of a line • A blank line is represented by two newlines together \n\n • It matters whether you press Enter at the end of the last line of the file – some methods in Python will treat the last line differently because of the \n character