The below are some more practice problems for handling text files, using what I learnt in my previous post:
Additional Practices
- Read all lines in a text file
'''with opening of the random.txt file, to read, as f''' with open('random.txt','r') as f: '''while the file is open and can be read''' while True: '''set variable 'lines' = read one line in the text file''' lines = f.readline() '''if lines i.e. if able to read one line in the text file, then print the line''' if lines: print(lines) '''else, break''' else: break
- Read first n lines of a file
- Using readlines( )
'''find n from user''' number = int(input('Number:')) '''set i=0''' i=0 '''opening of the text file & to read, set as f''' with open('random.txt','r') as f: '''set 'lines' variable to read all lines in the file''' lines = f.readlines() '''for every line in all the lines''' for line in lines: '''i + 1 every time it goes to a new line''' i+=1 '''if lines are being read and i<= user input n, print the line ''' if i<=number: print(line) ''' should break out of the loop after there is no need to print''' '''else this solution will iterate through the entire file even if it does not have to print and i>n''' else: break
- Using readline( ):
'''find n from user''' number = int(input('Number:')) '''set i=0''' i=0 '''opening of the text file & to read, set as f #while text file is open''' with open('random.txt','r') as f: '''while text file is open and can be read''' while True: '''set 'lines' variable to read line by line in the file''' lines = f.readline() '''if i < user input n''' if lines and i<number: '''i + 1, print the line''' i += 1 print(lines) '''else, if i not < n, break''' else: break
- Using readlines( )
- Append text to a file and display the text
sentence = "This is a new sentence" '''when file is open and we want to append''' with open('random.txt','a') as f: '''append "next line"''' f.write("\n") '''append the new sentence''' f.write(sentence)
- Read all lines
'''opening of the text file & to read, set as f''' with open('random.txt','r') as f: '''set 'lines' variable to all lines in the file''' lines = f.readlines() '''for every line in lines''' for line in lines: '''print the line''' print(line)
Thoughts
I am now more prepared to handle text files in Python.
One of the more important things I learnt is to use the ‘break’ statement as needed or the code would not be efficient if I leave the code to iterate beyond the necessary texts.
I also noticed that for .readline( ), it needs to be used within a ‘while’ loop as we want to read line by line. This is as we don’t know how many lines are in the file until it reaches break.
However, a ‘while’ loop is not necessary for .readlines( ) which retrieves all the content in the text file as a list of strings.