A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/os_open.htm below:

Python os.open() Method

Python os.open() Method

Python method os.open() opens the specified file and returns a corresponding file descriptor. It also allows us to set various flags and modes to files. Always remember the default mode is 0o0777 (octal), which set the file permissions to read, write, and execute by everyone.

Syntax

Following is the syntax for Python os.open() method −

os.open(file, flags, mode, *, dir_fd);
Parameters

The Python os.open() method accepts the following parameters −

Return Value

The Python os.open() method returns the file descriptor for the newly opened file.

Example

The following example shows the usage of open() method. Here, we are opening a file named "newFile.txt" by providing read-only access.

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDONLY )

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:", str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

The above code will open a file and read the content of that file −

File contains the following string: b'Tutorialspoint'
File closed successfully!!
Example

In the following example, we are opening a file with read and write access. If the specified file doesn't exist, the open() method will create a file with the same name.

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, b"This is tutorialspoint")

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:")
print(str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

On executing the above code, it will print the following result −

File contains the following string:
b'This is tutorialspoint'
File closed successfully!!

python_files_io.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4