![]() Next, check line by line for a particular string. ![]() with open("D://file.txt", "r+") as f:įirst, open the file for both reading and writing ( r+). We don’t want the last line to be present inside the file, so we need to replace it. We want to add two new lines: 4th and 5th. For example, if it contains a specific text and replaces it with a different one if the condition is met. Let’s imagine a situation where you want to check if the last line of the file meets certain criteria. The “append” file access mode ads new lines at the end of the file. If you change “a+” to “a”, and try to run the read() function, Python will return an error: io.UnsupportedOperation: not readable Append to a file, but overwrite the last line If you try to run the following code, the second line is not going to be placed before the first one. It’s important to mention, that the pointer is placed there only for reading. If you run the code, the two first characters are missing from the first line (indexing starts from 0). This value represents the number of places that the pointer moves to the right. First, delete the file and run this code: file_path = 'D://file.txt'īy opening the file for appending and reading, we can use the seek() function to enter the position of the pointer as a parameter. This mode allows you to append to a file but also read it at the same time.
0 Comments
Leave a Reply. |