Open In App

Python | os.sendfile() method

Last Updated : 26 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.sendfile() method in Python is used to copy specified number of bytes from specified source file descriptor to specified dest file descriptor starting from specified offset.
This method returns the total number of bytes sent and if EOF (end of file) is reached, it returns 0.

Syntax: os.sendfile(dest, source, offset, count)

Parameters:
dest: A file descriptor representing destination file.
source: A file descriptor representing source file
offset: An integer value representing starting position. Bytes to be sent will be counted from this position.
count: An integer value denoting total number of bytes to be sent from source file descriptor.

Return Type: This method returns an integer value which represents the total of bytes sent from source file descriptor to dest file descriptor. 0 is returned if EOF is reached.

Consider the below text as the content of the file named ‘Python_intro.txt’.

Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.

Code: Use of os.sendfile() method




# Python program to explain os.sendfile() method 
  
# importing os module 
import os
  
  
# Source file path
source = './Python_intro.txt'
  
# destination file path
dest = './newfile.txt'
  
# Open both files and get
# the file descriptor
# using os.open() method
src_fd = os.open(source, os.O_RDONLY)
dest_fd = os.open(dest, os.O_RDWR | os.O_CREAT)
  
# Now send n bytes from
# source file descriptor
# to destination file descriptor
# using os.sendfile() method
offset = 0
count = 100
bytesSent = os.sendfile(dest_fd, src_fd, offset, count)
print("% d bytes sent / copied successfully." % bytesSent)
  
# Now read the sent / copied
# content from destination
# file descriptor 
os.lseek(dest_fd, 0, 0)
str = os.read(dest_fd, bytesSent)
  
# Print read bytes
print(str)
  
# Close the file descriptors
os.close(src_fd)
os.close(dest_fd)


Output:

100 bytes sent/copied successfully.
b'Python is a widely used general-purpose, high level programming language.
It was initially designed '

Reference: https://docs.python.org/3/library/os.html#os.sendfile


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads