how to open and write a file in python? | applied electronics engineering


how to open and write a file in python?

By Applied Electronics - Saturday, March 4, 2017 No Comments
Sooner or later you want to work with files in python. Here we show how to open and write a file in python.

In python everything is an object and belongs to some classes. Likewise so, a file is also an object in python programming language. That means when you want to work with files in python you need to create file object, then use functions like write and read. The file object is created using the open function and passing processing mode like w for write. The following example shows how to open and create a file called data.txt, write some data into the file and then close the file.

The first statement creates a file named data.txt and w is the processing mode meaning write. This line also create the object called f. Then in the second line the write method for file object f is used to write text into the file. The third statement does the same but writes world word. Then the last statement closes the file object f, destroying it from the memory.

Now suppose you want to read the file data.txt. Then again you create a file object f and use the open function to load the file data into python. In case of reading file, the processing mode to be passed as argument to the open is r but this is optional because read mode is optional. So for example to import or read the file data.txt you would do so in the following way.

So in this way you can open and write a file in python programming language.

See also 3 steps to reading text files in python. For book see learning robotics using python pdf.

No Comment to " how to open and write a file in python? "