Sunday 6 December 2015

Python - Create text file, write to text file, read from text file, append to text file

Create text file and write to text file.

'Modes' of opening a file: r, rb r+, rb+, w, wb, w+, wb+, a, ab, a+, ab+, 
File object 'attributes': file.closed, file.mode, file.name, file.softspace

List of the different modes of opening a file, file Object Attributes
http://www.tutorialspoint.com/python/python_files_io.htm

Sample Program:
import os
fileNameAndPath = os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/SampleTextFile.txt'))
with open(fileNameAndPath, "w") as f : f.write("aaa 123 bbb 456 ccc 789")






Read from text file.

'Modes' of opening a file: r, rb r+, rb+, w, wb, w+, wb+, a, ab, a+, ab+, 
File object 'attributes': file.closed, file.mode, file.name, file.softspace

List of the different modes of opening a file, file Object Attributes
http://www.tutorialspoint.com/python/python_files_io.htm

Sample Program
import os

fileNameAndPath = os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/SampleTextFile.txt'))
with open(fileNameAndPath,'r') as f: k=f.read()

print (k)    

Note:
File should be closed before executing the script.



Append text to text file.

'Modes' of opening a file: r, rb r+, rb+, w, wb, w+, wb+, a, ab, a+, ab+, 
File object 'attributes': file.closed, file.mode, file.name, file.softspace

List of the different modes of opening a file, file Object Attributes

Sample Program
import os

fileNameAndPath = os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/SampleTextFile.txt'))
with open(fileNameAndPath, "a") as myfile: myfile.write("\nappended text here ....")

Note:
File should be closed before executing the script.

Open the file after executing the script.

No comments:

Post a Comment