Mastering File Reading in Python: A Step-by-Step Guide
School
Tri-Village**We aren't endorsed by this school
Course
MATHAMATICS 11TH
Subject
Computer Science
Date
Dec 12, 2024
Pages
2
Uploaded by xunanglao02
I'm already much better at Python. Figure 1-10. Text file, file_to_read.txt, in Notepad++ (Windows) 3. Save the file to your Desktop as file_to_read.txt. 4. Add the following lines of code at the bottom of first_script.py: # READ A FILE # Read a single text file input_file = sys.argv[1] print "Output #143: filereader = open(input_file, 'r') for row in filereader: print row.strip() filereader.close() The first line in this example uses the sys.argv list to capture the path to the file we intend to read and assigns the path to the variable input_file. The second line creates a file object, filereader, which contains the rows resulting from opening the input_filein 'r' (read) mode. The for loop in the next line reads the rows in the filereader object one at a time. The body of the for loop prints each row, and the strip function removes spaces, tabs, and newline characters from the ends of each row before it is printed. The final line closes the file reader object once all of the rows in the input file have been read and printed to the screen. 5. Resave first_script.py. ReadingaTextFile | 45
6. To read the text file, type the following line, as shown in Figure 1-11, and then hit Enter: python first_script.py file_to_read.txt Figure 1-11. Python script and the text file it will process in a Command Prompt window At this point, you've now read a text file in Python. You should see the following printed at the bottom of your screen, beneath any other previous output (Figure 1-12): I'm already much better at Python. 46 | Chapter 1: Python Basics