Introduction
Printing selected elements from a file can be a useful way to quickly access the information you need. Whether you are looking to print out a specific line from a text file or a specific column from a CSV file, there are a few different methods you can use to achieve this. In this article, we will discuss how to print selected elements from a file using various methods in Python. We will also discuss the advantages and disadvantages of each method. By the end of this article, you should have a better understanding of how to print selected elements from a file.
Solution
Using Python, you can print selected elements from a file by using the following code:
with open(‘filename.txt’, ‘r’) as f:
for line in f:
elements = line.split()
if elements[0] == ‘element_to_print’:
print(elements[1])
Here is one way:
with open("fk.txt") as file: # Use file to refer to the file object
data = file.readlines()
column1, column2 = [], []
for line in data:
try:
entry1, entry2 = line.split(' ')
column1.append(int(entry1))
column2.append(int(entry2))
except ValueError:
pass
print column1, column2
2
solved How to print selected elements from file?
#include <stdio.h> int main() { FILE *fp; char ch; int line_num = 1; int find_result = 0; fp = fopen("test.txt", "r"); if (fp == NULL) { return(-1); } while((ch = fgetc(fp)) != EOF) { if (ch == '\n') { line_num++; } if (find_result == 0) { if (ch == 'a') { find_result = 1; } } else { if (ch == 'b') { printf("Line Number [%d]\n", line_num); find_result = 0; } } } if (fp) { fclose(fp); } return(0); }
This code snippet shows how to print selected elements from a file. The code begins by including the stdio.h header file and declaring a main function. The code then opens a file called test.txt in read mode and assigns the file pointer to the fp variable.
The code then enters a while loop which reads each character from the file until the end of the file is reached. The code checks if the character is a new line character and if so, increments the line_num variable. The code then checks if the character is an ‘a’ and if so, sets the find_result variable to 1. If the find_result variable is 1, the code checks if the character is a ‘b’ and if so, prints the line number and sets the find_result variable to 0.
Finally, the code closes the file and returns 0. This code snippet shows how to print selected elements from a file.