Зміст курсу
Python Advanced Concepts
Python Advanced Concepts
Advanced File Operations
Appending to a File
Appending is used when you want to add data to the end of an existing file without overwriting its current contents. This is done by opening the file in append mode ('a'
).
In this example, \nBonjour!
is added to the end of greetings.txt
.
Note
The
\n
character represents a newline. For example, in the context of writing to or reading from a file, appending\n
at the end of a string ensures that the next piece of text will start on a new line, making the content easier to read and properly formatted.
Random Access
Random access allows you to read or write data at any position within the file. This is particularly useful in applications where you don't need to process data sequentially.
Using seek() Method
The seek()
method is used to move the file pointer to a specific position in the file, which is crucial for random access:
In this example, the file.seek(10) command moves the file's read cursor to the 10th byte position, skipping the first 9 characters.
If you've reached the end of the file and need to start over, the seek()
method without any arguments or with 0
zero can reset the file pointer back to the beginning:
Using tell() Method
The tell()
method is used to find the current position of the file pointer within the file. This is helpful when you need to keep track of where you are in the file, especially after random access operations.
Дякуємо за ваш відгук!