Tuesday, April 29, 2014

11. Python Files

Most of the file operations in Python will involve text files. Here we will go over statements for writing and reading of text files.




For reading or writing, we have to have a File object which is created by the open() function. For writing of files, the mode will be 'w', and to append to the end of a file it is the mode 'a'. We can only write out Strings. There are two functions to write to File object. Here we write the String “Hello Python” to the File object. Finally, we should close the File object. Closing will finalize the writing to the actual file.




To write a multiline String, we have to include \n (which stands for the newline character) at the end of each line.




This is the text which was created in the last program.




For writing out multi-line Strings, it is better to use the writelines() function. Here, we append the four lines to a List. Since each is only one line, there is only one \n character.




We can also define the List at once. Notice Python easily understands this is the same statement, since it has not found a closing square bracket. This should be used often to make the program structure readable.




For reading, there are three functions. If the function read() is used, it will read the entire file and return it in a String.




If the read() function is used with a number inside the parenthesis, it will only read that number of characters. This is important if we have fields of certain width.




We can read the entire line, that is until the first newline character with the readline() function. We should see that the newline character is always at the end of Strings which are returned.




Finally, we have the readlines() function. This will read all the lines at once into a List. Most of the time this function is used in reading text files, as it breaks down the file into smaller strings.




You will find additional information, including a larger image of the slides and text, at pythonaudio.blogspot.com.




This is the video of Tutorial 11:



1 comment:

  1. nice article to improve knowledge.thank you.keep blogging.
    web programming tutorial
    welookups

    ReplyDelete

About Me

I have used Python for the last 10+ years. I have a PhD in Electrical Engineering. I have taught Assembly Language programming of Intel-compatible chips as well as PC hardware interfacing. In my research, I have used Python to automate my calculations in physics and chemistry. I also use C++ and Java, often with Python.