Write a Python program to read a text file and display words that are ending with alphabet x
Python String: Exercise-12 with SolutionWrite a Python program to count the occurrences of each word in a given sentence. Show
Sample Solution:- Python Code: def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog.'))Sample Output: {'the': 2, 'jumps': 1, 'brown': 1, 'lazy': 1, 'fox': 1, 'over': 1, 'quick': 1, 'dog.': 1}Flowchart: Visualize Python code execution:The following tool visualize what the computer is doing step-by-step as it executes the said program: Python Code Editor: Have another way to solve this solution? Contribute your code (and comments) through Disqus. Previous: Write a Python program to remove the
characters which have odd index values of a given string. Python: Tips of the DayDifference In Sets: To retrieve the difference between two sets: a = {1,2,3} b = {3,4,5}w c = a.difference(b)
Why do we want to read and write files?Being able to open and read in files allows us to work with larger data sets, where it wouldn’t be possible to type in each and every value and store them one-at-a-time as variables. Writing files allows us to process our data and then save the output to a file so we can look at it later. Right now, we will practice working with a comma-delimited text file (.csv) that contains several columns of data. However, what you learn in this lesson can be applied to any general text file. In the next lesson, you will learn another way to read and process .csv data. Paths to filesIn order to open a file, we need to tell Python exactly where the file is located, relative to where Python is currently working (the working directory). In Spyder, we can do this by setting our current working directory to the folder where the file is located. Or, when we provide the file name, we can give a complete path to the file.
The File SetupLet’s open and examine the structure of the file Plates_output_simple.csv. If you open the file in a text editor, you will see that the file contains several lines of text. However, this is fairly difficult to read. If you open the file in a spreadsheet program such as LibreOfficeCalc or Excel, you can see that the file is organized into columns, with each column separated by the commas in the image above (hence the file extension .csv, which stands for comma-separated values). The file contains one header row, followed by eight rows of data. Each row represents a single plate image. If we look at the column headings, we can see that we have collected data for each plate:
We will read in this data file and then work to analyze the data. Opening and reading files is a three-step processWe will open and read the file in three steps.
And then, there’s one more step to do!
You can think of these three steps as being similar to checking out a book from the library. First, you have to go to the catalog or database to find out which book you need (the filename). Then, you have to go and get it off the shelf and open the book up (the open function). Finally, to gain any information from the book, you have to read the words (the read function)! Here is an example of opening, reading, and closing a file. #Create a variable for the file name filename = 'Plates_output_simple.csv' #This is simply a string of text #Open the file infile = open(filename, 'r') # 'r' says we are opening the file to read, infile is the opened file object that we will read from #Store the data from the file in a variable data = infile.read() #Print the data in the file print(data) #close the file infile.close() Once we have read the data in the file into our variable data, we can treat it like any other variable in our code.
Commands for reading in filesThere are a variety of commands that allow us to read in data from files. Mixing these commands can have some unexpected results. #Create a variable for the file name filename = 'Plates_output_simple.csv' #Open the file infile = open(filename, 'r') #Print the first two lines of the file print(infile.readline()) print(infile.readline()) #call infile.read() print(infile.read()) #close the file infile.close() Notice that the infile.read()command started at the third line of the file, where the first two infile.readline() commands left off. Think of it like this: when the file is opened, a pointer is placed at the top left corner of the file at the beginning of the first line. Any time a read function is called, the cursor or pointer advances from where it already is. The first infile.readline() started at the beginning of the file and advanced to the end of the first line. Now, the pointer is positioned at the beginning of the second line. The second infile.readline() advanced to the end of the second line of the file, and left the pointer positioned at the beginning of the third line. infile.read() began from this position, and advanced through to the end of the file. In general, if you want to switch between the different kinds of read commands, you should close the file and then open it again to start over. Reading all of the lines of a file into a listinfile.readlines() will read all of the lines into a list, where each line of the file is an item in the list. This is extremely useful, because once we have read the file in this way, we can loop through each line of the file and process it. This approach works well on data files where the data is organized into columns similar to a spreadsheet, because it is likely that we will want to handle each line in the same way. The example below demonstrates this approach: #Create a variable for the file name filename = "Plates_output_simple.csv" #Open the file infile = open(filename, 'r') lines = infile.readlines() for line in lines: #lines is a list with each item representing a line of the file if 'control' in line: print(line) #print lines for control condition infile.close() #close the file when you're done! Using .split() to separate “columns”Since our data is in a .csv file, we can use the split command to separate each line of the file into a list. This can be useful if we want to access specific columns of the file. #Create a variable for the file name filename = "Plates_output_simple.csv" #Open the file infile = open(filename, 'r') lines = infile.readlines() for line in lines: sline = line.split(',') # separates line into a list of items. ',' tells it to split the lines at the commas print(sline) #each line is now a list infile.close() #Always close the file!
Writing data out to a fileOften, we will want to write data to a new file. This is especially useful if we have done a lot of computations or data processing and we want to be able to save it and come back to it later. Writing a file is the same multi-step processJust like reading a file, we will open and write the file in multiple steps.
The code below gives an example of writing to a file: filename = "output.txt" #w tells python we are opening the file to write into it outfile = open(filename, 'w') outfile.write("This is the first line of the file") outfile.write("This is the second line of the file") outfile.close() #Close the file when we’re done!
Newline charactersWhen you examine the file you just wrote, you will see that all of the text is on the same line! This is because we must tell Python when to start on a new line by using the special string character '\n'. This newline character will tell Python exactly where to start each new line. The example below demonstrates how to use newline characters: filename = 'output_newlines.txt' #w tells python we are opening the file to write into it outfile = open(filename, 'w') outfile.write("This is the first line of the file\n") outfile.write("This is the second line of the file\n") outfile.close() #Close the file when we’re done! Go open the file you just wrote and and check that the lines are spaced correctly.:
Writing numbers to filesJust like Python automatically reads files in as strings, the write()function expects to only write strings. If we want to write numbers to a file, we will need to “cast” them as strings using the function str(). The code below shows an example of this: numbers = range(0, 10) filename = "output_numbers.txt" #w tells python we are opening the file to write into it outfile = open(filename, 'w') for number in numbers: outfile.write(str(number)) outfile.close() #Close the file when we’re done!
How do you display data from a text file in Python?To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object.
...
1) open() function.. How do you read a file and display its contents in Python?Python Program to Read the Contents of the File. Take the file name from the user.. Use readline() function for the first line first.. Use a while loop to print the first line and then read the remaining lines and print it till the end of file.. How do you read and write data from a text file in Python?There are 6 access modes in python.. Read Only ('r') : Open text file for reading. ... . Read and Write ('r+'): Open the file for reading and writing. ... . Write Only ('w') : Open the file for writing. ... . Write and Read ('w+') : Open the file for reading and writing. ... . Append Only ('a'): Open the file for writing.. How do you read until the end of a file in Python?The readlines () method is the most popular method for reading all the lines of the file at once. This method reads the file until EOF (End of file), which means it reads from the first line until the last line. When you apply this method on a file to read its lines, it returns a list.
|