Pythonschlange | os.ftruncate()-Methode
OS-Modul in Python bietet Funktionen für die Interaktion mit dem Betriebssystem. Das Betriebssystem gehört zu den Standard-Utility-Modulen von Python. Dieses Modul bietet eine portable Möglichkeit, betriebssystemabhängige Funktionen zu verwenden. os.ftruncate()
-Methode kürzt die Datei, die dem Dateideskriptor fd entspricht , sodass sie höchstens eine Länge von Bytes hat.
Syntax: os.ftruncate(fd, Länge)
Parameter:
fd: Dies ist der Dateideskriptor, der abgeschnitten werden soll.
Länge: Dies ist die Länge der Datei, bis zu der die Datei gekürzt werden soll.Rückgabewert: Diese Methode gibt keinen Wert zurück.
Beispiel Nr. 1:
Methode os.ftruncate()
verwenden, um eine Datei zu kürzen
# Python program to explain os.ftruncate() method # importing os module import os # path path = 'C:/Users/Rajnish/Desktop/testfile.txt' # Open the file and get # the file descriptor associated # with it using os.open() method fd = os.open(path, os.O_RDWR|os.O_CREAT) # String to be written s = 'GeeksforGeeks' # Convert the string to bytes line = str.encode(s) # Write the bytestring to the file # associated with the file # descriptor fd os.write(fd, line) # Using os.ftruncate() method os.ftruncate(fd, 5) # Seek the file from beginning # using os.lseek() method os.lseek(fd, 0, 0) # Read the file s = os.read(fd, 15) # Print string print(s) # Close the file descriptor os.close(fd)
# Python program to explain os.ftruncate() method # importing os module import os # path path = 'C:/Users/Rajnish/Desktop/testfile.txt' # Open the file and get # the file descriptor associated # with it using os.open() method fd = os.open(path, os.O_RDWR|os.O_CREAT) # String to be written s = 'GeeksforGeeks - Computer Science portal' # Convert the string to bytes line = str.encode(s) # Write the bytestring to the file # associated with the file # descriptor fd os.write(fd, line) # Using os.ftruncate() method os.ftruncate(fd, 10) # Seek the file from beginning # using os.lseek() method os.lseek(fd, 0, 0) # Read the file s = os.read(fd, 15) # Print string print(s) # Close the file descriptor os.close(fd)