sampleqa.in tutorials, Python Programming  tutorial,
	      Python File Handling

Python File Handling


   

File is an entity in persistent storage device, It has name,size,creation time,owner ,path to access that file etc., There are various types of files exists in the System, file types can .Docx, *.PDF, *.TXT, .CSV , .XLS etc.,

Python supports file operations on text files and binary files

Python includes File Operations in io module. Reading Text / binary files, Writing text / binary content into a file.

  • Reading from File
  • Writing to a File
How to deal with Directories in Python
  • Get current directory
  •     os module has method called getcwd() cwd means current working directory.

    				import os;
    				localdir = os.getcwd()
    				print("Current Working Directory"," is ", localdir)
    			
  • Absolute Path
  • Abosulte Path is a path from root directory

  • Relative Path
  • Relative Path means , where or directory it is located in for ex: ./file.txt or ~/file.txt ./file.txt this file is located in current directory ~/file.txt this file is located in user's home directory.

  • Permissions
  • Every file and directory has its own permission set, Like READ,WRITE and EXECUTE.

To read or write into a file, Python framework provides a method called open

open method creates a file if not exists, or opens a file if it exists in the HDD,USB etc., open method syntax:
		open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
 		returns Stream
 		
 		file   name of the file absolute or relative path
 		mode default mode is read 'r', it can be 'w', 'a', 'rb','wb','ab'
 		encoding if you have characters other than ASCII, encoding must be provided
 		errors how encoding errors are handled
 		closeFd File Descriptor should be close or not for further use.
		

Open method returns file object, using which user can read ,write and append content to the file.

Reading from a File

			fp=open('file.txt',mode='r',encoding='UTF-8')
			print(fp.readlines())
			fp.close()
		
		

Writing into a File

			fp=open('file.txt',mode='w',encoding='UTF-8')
			fp.write('Hello')
			fp.write('Today I used Chatbot')
			fp.write('Nice experience')
			fp.close();
		

Appending content to a File

			fp=open('file.txt',mode='a',encoding='UTF-8')
			fp.write('chatbot writes programs for us');
			fp.write('chatbot is pre-programmed tool')
			fp.close();
		

Copy a Binary File

Binary files always use 'b' mode to indicate binary content, along with read(r),write(w),append(a)

	>>> fpSource = open("/home/peter//Pictures/img1.jpg","rb")
	>>> fpDestination = open("/home/peter//MyPictures/img1.jpg","wb")

	>>> b = fpSource.read()
	>>> fpDestination.write(b)
	19723
	>>> fpSource.close();fpDestination.close();
	>>> 
		

Find End of the File

file seek and tell functions allows us to find End-Of-File in Python

		EOF = fp.seek(0,2)
		print("End of the File {}".format(EOF))
		
		tell() methods gives, offset value(i.e from beginning of the file, which starts from 0)
	

Read or Write Files using with Clause

	
	

ADS