Python, like any programming language, is able to work with files. The function used to open a file (to read or to write) is open()
which needs the path of the file with the file name and then the mode. The three most used modes are 'r' to read a file, 'w' to write a file and 'a' to append to a file. The output of this function is a file handler which can be used to read or write depending on the selected mode. Once some operations have been done the file needs to be closed so that it is possible to see the modifications performed and modify the file from the Operating System.
Once the file handler is created it is possible to use the method read()
to read the whole file or read(n)
to read $n$ characters. On the other hand, if the file is formed by several lines (like a list), a useful method is readline()
which only reads the file line by line while readline()
. The code below provides some examples.
#Example of file #Let's assume this file contains "Hello ValianTek World!" file_path="filename.txt" f = open(file_path,'r') # By default it is 'r', so it can be omitted text=f.read() # Gets the full text in the file print(text) # Prints "Hello ValianTek World!" f.close() # Close the file #Open again f = open(file_path) # By default is 'r' text2=f.read(5) # Gets the first 5 characters print(text2) # Prints "Hello" f.close() # Close the file
In case of lists, a useful method is readline()
which only reads the file line by line while readlines()
outputs the full list of lines as shown below.
#Example of file 2 #Let's assume the file contains: #This #is #a #test! file_path="filename2.txt" f = open(file_path) line=f.readline() # Gets the first line print(line) # Prints "This" but also considers the new line line2=f.readline() # Gets the second line #To remove the newline from the string, we can use the method "strip" as shown below print(line2.strip("\n")) # Prints "is" without leaving a blank line below f.close() # Close the file f = open(file_path) lines=f.readlines() # This is a list of all the lines in the file print(lines) # Prints ['This\n', 'is\n', 'a\n', 'test!'], the '\n' is the new line f.close()
In case of a list or data in several rows, it is also possible to use for loops to scan automatically through the list.
#Assuming to use the same file used above file_path="filename2.txt" f = open(file_path) for i in f: # For Loop of elements in f print(i) # Print elements one by one f.close()
If the user does not want to close the file it is possible to use the keyword with
and then the file is closed automatically once the code included within this keyword is executed.
file_path="filename2.txt" with open(file_path) as f: print(f.read()) # Prints the full text with open(file_path) as f: lines=f.readlines() # Saves the lines print(lines) # Prints the list
There are many ways to access the file, use the one more suitable for your task.
To write a file it needs to be opened by using 'w'
and then the methods that need to be used are write()
, which writes a string into a text file, and writelines()
which writes a list of strings (more generally any iterable object like tuples or sets). The way with
and the for loops are used is similar to the "read" case.
#Write this file file_path="filename3.txt" f = open(file_path,'w') # Use 'w' to write the file f.write("Hello ValianTek World!\n") # The "\n" is added to go to a new line. f.write("This is a test!") # The "\n" is not added because the file is now ended f.close() # Close the file #Write another file file_path="filename4.txt" lines=["Hello!\n","This\n","is\n","another\n","test!"] # Again, the "\n" is added to have a new line with open(file_path,'w') as f: f.writelines(lines) # Writes all the lines in the file and closes it lines=["Hello","ValianTek","World"] #Here we did not add the "\n" with open(file_path,'w') as f: for line in lines: f.write(line) # Write lines one by one f.write("\n") # We can add this separately, note that it will also add one with the last word
As it is possible to see, there are several ways to write some content into files.
By using 'w'
a file can be written and, in case the same name of file is used, it is then overwritten. On the other hand, by using 'a'
the new parts are appended at the bottom of the file without deleting anything already written in the file. All the considerations done until now are valid also for appending some text to files and the methods write()
and writelines()
are used.
#Write on this new file file_path="filename5.txt" with open(file_path,'a') as f: # If the file does not exist, with 'a' it is created (works like 'w') f.write("I am writing on this new file!\n") # This is the first line of the file lines=["This is the second line!\n", "We end the file with this line!"] # Create a couple of lines with open(file_path,'a') as f: # We open the file again and append other two lines f.writelines(lines) # Append both the lines, now the file has 3 lines
To delete files the library "os" needs to be imported and the method remove()
needs to be used with the file path as input. This method, however returns an error if the file does not exist. A couple of ways to address this is by:
try: ... except:
exception handlingos.path.exists()
which returns True if the file existsimport os # Imports the library #Assuming for example that file_path="filename6.txt" os.remove(file_path) # This removes the file found in file_path #The code below can generate an error if "filename6.txt" does not exist. #We can avoid it with try...except... try: os.remove(file_path) except: print("File does not exist!") #Or with os.path.exists() if(os.path.exists(file_path)): # If the method returns True.... os.remove(file_path) else: print("File does not exist!")
This concludes the overview on the basic operations that can be performed on Python. Try these functions and the different ways to handle the files. You need to test it on your on computer given that involves writing/reading/deleting files that will be saved on your hard drive.