Can you read and append file at the same time python?
Show I tried these, but got errors:
error:
TrebledJ 8,0627 gold badges23 silver badges46 bronze badges asked May 30, 2019 at 15:19
1 You're looking for the With
If you ever need to do an entire reread, you could return to the starting position by doing
answered May 30, 2019 at 15:39
You can't do that with a textfile. Either you want to read it or you want to write to
it. The Textfiles in general can't be updated in place. You can use After that
you have two files so you have to take care of deleting the old one. If that is troublesome, take a look at the module The other alternative is to read the input file into memory, close and reopen it for writing, then write out a new version of the file. Then you don't have to delete the old copy. But if something goes wrong in the middle you will have no old input file, because you deleted it, and no new output file either, because you didn't successfully write it. The reason for this is that textfiles are not designed for random access. answered May 30, 2019 at 15:28
BoarGulesBoarGules 15.8k2 gold badges29 silver badges42 bronze badges In this article, we will discuss how to append text or new lines to an existing file using python.
file_object = open('sample.txt', 'a') With file access mode ‘a’, open() function first checks if file exists or not. If the file doesn’t exist, then it creates an empty file and opens it. Whereas, if the file already exists then it opens it. In both cases, it returns a file object, and it has write cursor, which points to the end of the opened file. Now, if you write anything to the file using this file object, then it will be appended to the end. Let’s use this to append text at the end of a file, Suppose we have a file ‘sample.txt,’ and its contents are, Hello this is a sample file It contains sample text This is the end of file Now let’s append text ‘hello’ at the end of this file, # Open a file with access mode 'a' file_object = open('sample.txt', 'a') # Append 'hello' at the end of file file_object.write('hello') # Close the file file_object.close() Contents of the file ‘sample.txt’ will be now, Hello this is a sample file It contains sample text This is the end of filehello We opened the file ‘sample.txt’ in append mode i.e. using access mode ‘a’. As cursor was pointing to the end of the file in the file object, therefore when we passed the string in write() function, it appended it at the end of the file. So, our text ‘hello’ gets added at the end of the file ‘sample.txt’. Append a text to file in Python using ‘with open’ statementWe can open the file in append access mode i.e. ‘a’, using ‘with open’ statement too, and then we can append the text at the end of the file. # Open a file with access mode 'a' with open("sample.txt", "a") as file_object: # Append 'hello' at the end of file file_object.write("hello") Contents of the file ‘sample.txt’ will be now, Hello this is a sample file It contains sample text This is the end of filehellohello Text ‘hello’ gets again added at the end of file ‘sample.txt’. Advertisements In both the above examples, the text gets added at the end of the file. But as we can see, it is not appended as a new line. There might be scenarios when we want to add data to a file as a new line. Append data to a file as a new line in PythonSolution for this is a little tricky here. let’s start with the basic approach and then we will discuss drawback in it and see how to improve over it, Basic approach
Well this approach works fine if our file already exists and already has some data in it. But if the file doesn’t exist or file is empty then this approach will fail because contents of the file will be like this, …………………….. New added Line It first writes an empty line and then writes our line. But in this case, only appending a line was fine, we don’t need to write ‘\n’ before that. So, our final approach should be like this,
This solution will work fine in both scenarios. Let’s use this solution to append a newline at the end of the file. Suppose we have a file ‘sample2.txt’ with
following contents, Hello this is a sample file It contains sample text This is the end of file Append new line to the file, # Open the file in append & read mode ('a+') with open("sample2.txt", "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0 : file_object.write("\n") # Append text at the end of file file_object.write("hello hi") Contents of the file ‘sample2.txt‘ now, Hello this is a sample file It contains sample text This is the end of file hello hi A new line is appended at the end of the file. File access mode ‘a+’, creates opens the file for both read and writing. Also if file it doesn’t exist, and then it creates the file too. Let’s move the code to a separate function, def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0: file_object.write("\n") # Append text at the end of file file_object.write(text_to_append) Let’s use this function to append one more line to a file that doesn’t exist # Append one line to a file that does not exist append_new_line('sample3.txt', 'This is first line') Contents of the file ‘sample3.txt’ will be now, This is first line It confirms that it didn’t append ‘\n’ before writing a new line because the file was already empty. Now let’s again append another line to the same
file to check if it works fine, # Append another line to a file that already exist & has some contents append_new_line('sample3.txt', 'This is second line') Contents of the file ‘sample3.txt’ will be now, This is first line This is second line As file already exist and has contents too; therefore it first appended the ‘\n’ into the file and then our given line. Append multiple lines to a file in PythonSuppose we have a list of string, list_of_lines = ['First Line', 'Second Line', 'Third Line'] Now we want to append each element in the list as a line in the file. How to do that? We could do that by calling above created function
append_new_line() multiple times, but it is not an optimized solution because it will open and close the file for each element in the list.
Basically we don’t need to write first ‘\n’ if the file is empty. A function to append multiple lines in a file is, def append_multiple_lines(file_name, lines_to_append): # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: appendEOL = False # Move read cursor to the start of file. file_object.seek(0) # Check if file is not empty data = file_object.read(100) if len(data) > 0: appendEOL = True # Iterate over each string in the list for line in lines_to_append: # If file is not empty then append '\n' before first line for # other lines always append '\n' before appending line if appendEOL == True: file_object.write("\n") else: appendEOL = True # Append element at the end of file file_object.write(line) Now let’s use this function. This is first line This is second line We have a list of strings, list_of_lines = ['First Line', 'Second Line', 'Third Line'] Append all the strings in this list as separate lines at the end of file ‘sample3.txt’ # Append strings in list as seperate new lines in the end of file append_multiple_lines('sample3.txt', list_of_lines) Now contents of file ‘sample3.txt’ is, This is first line This is second line First Line Second Line Third Line It appended all the strings in the given list as newlines in the file. The complete example is as follows, def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0: file_object.write("\n") # Append text at the end of file file_object.write(text_to_append) def append_multiple_lines(file_name, lines_to_append): # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: appendEOL = False # Move read cursor to the start of file. file_object.seek(0) # Check if file is not empty data = file_object.read(100) if len(data) > 0: appendEOL = True # Iterate over each string in the list for line in lines_to_append: # If file is not empty then append '\n' before first line for # other lines always append '\n' before appending line if appendEOL == True: file_object.write("\n") else: appendEOL = True # Append element at the end of file file_object.write(line) def main(): print('Append a text to file in Python') # Open a file with access mode 'a' file_object = open('sample.txt', 'a') # Append 'hello' at the end of file file_object.write('hello') # Close the file file_object.close() print('Append a text to file in Python using "with statement"') # Open a file with access mode 'a' with open("sample.txt", "a") as file_object: # Append 'hello' at the end of file file_object.write("hello") print('Append data to a file as a new line in Python') # Open the file in append & read mode ('a+') with open("sample2.txt", "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then append '\n' data = file_object.read(100) if len(data) > 0 : file_object.write("\n") # Append text at the end of file file_object.write("hello hi") # Append one line to a file that does not exist append_new_line('sample3.txt', 'This is first line') # Append another line to a file that already exist & has some contents append_new_line('sample3.txt', 'This is second line') print('Append multiple lines to a file in Python') list_of_lines = ['First Line', 'Second Line', 'Third Line'] # Append strings in list as seperate new lines in the end of file append_multiple_lines('sample3.txt', list_of_lines) if __name__ == '__main__': main() Output: Append a text to file in Python Append a text to file in Python using "with statement" Append data to a file as a new line in Python Append multiple lines to a file in Python Can you read and write a file at the same time Python?Python makes it easy to read & write to files with the help of built-in functions. In this article, we will look at how to read & write text files that consist of individual lines of data separated by newline character (\n).
How do I open a file with appending in Python?Append data to a file as a new line in Python. Open the file in append mode ('a'). Write cursor points to the end of file.. Append '\n' at the end of the file using write() function.. Append the given line to the file using write() function.. Close the file.. How do you append a file to another file in Python?STEP 4: Close both the files and exit from the program.. name1 = input("Enter file to be read from: "). name2 = input("Enter file to be appended to: "). file = open(name1, "r"). data2 = file. read(). file. close(). fout = open(name2, "a"). fout. write(data2). fout. close(). |