How can I print only every 5th line

I have a text file ( "name_data.txt" ) that has the following contents:

 name: Kelo family name: Lam location: Asia members: Kelo, Kiko, Jil name: Miko family name: Naiton location: Japan members: Miko,Kayati 

The text file continues to work with the same template (first name, last name, location, members)

I want to print the first line, and then print every fifth line, so that at first only the line with the name is printed. Then I want to have a list of names

I need my conclusion:

 ["Kelo","Miko"] 

So far I have received (although this is wrong):

 name_data= load_local_file('name_data.txt',ignore_header=False,delimiter='\t') def __init __(name_reader): names=list() count=0 name_line=5 line_number=0 for name in name_data: if line_number<5: line_number +=1 if line_number ==5: names.append(line_number) 
+6
source share
6 answers

You can identify every fifth line by comparing linenumber modulo 5 with a number. In your case, it should be 0 , because you need the first line and the 6th, 11th, ... (note that python starts at index 0)

To get line numbers, as well as content that you can iterate over a file using enumerate .

Then, to discard part of the name: and save what happens after that, you can use str.split() .

A working implementation might look like this:

 # Create an empty list for the names names = [] # Opening the file with "with" makes sure it is automatically closed even # if the program encounters an Exception. with open('name_data.txt', 'r') as file: for lineno, line in enumerate(file): # The lineno modulo 5 is zero for the first line and every fifth line thereafter. if lineno % 5 == 0: # Make sure it really starts with "name" if not line.startswith('name'): raise ValueError('line did not start with "name".') # Split the line by the ":" and keep only what is coming after it. # Using `maxsplit=1` makes sure you don't run into trouble if the name # contains ":" as well (may be unnecessary but better safe than sorry!) name = line.split(':', 1)[1] # Remove any remaining whitespaces around the name name = name.strip() # Save the name in the list of names names.append(name) # print out the list of names print(names) 

Instead of listing, you can also use itertools.islice with a step:

 from itertools import islice with open('name_data.txt', 'r') as file: for line in islice(file, None, None, 5): ... # like above except for the "if lineno % 5 == 0:" line 

Depending on your needs, you can use the re module to fully analyze the file:

 import re # The regular expression group = re.compile(r"name: (.+)\nfamily name: (.+)\nlocation: (.+)\nmembers: (.+)\n", flags=re.MULTILINE) with open(filename, 'r') as file: # Apply the regex to your file all_data = re.findall(group, file) # To get the names you just need the first element in each group: firstnames = [item[0] for item in all_data] 

firstnames will be ['Kelo', 'Miko'] for your example and similar, if you use [item[1] for item in all_data] then you will get the last names: ['Lam', 'Naiton'] . To successfully use the regular expression, you must make sure that it really matches your file layout, otherwise you will get incorrect results.

+4
source

An easy way to do this would be to:

 with open('name_data.txt', 'r') as file: index = 0 for line in file: if index % 5 == 0: print(line.split()[1]) index += 1 
+2
source

You can do this on the same line as the list.

 c = open('test.txt', 'r').readlines() # for every fifth line extract out name and store in list a = [i.replace('name: ', '').replace('\n', '') for i in c[::5]] print(a) # ['Kelo', 'Miko'] 
+2
source

Assuming name_data is a list of lines in a file, you can do

 names = [] for i in range(1, len(name_data), 5): names.append(name_data[i].split(":")[1].strip()) 
+1
source

Having a name_data.txt file with data as follows: 1 2 3 4 5 6 7 8 9 10

Here you can print the first and every fifth line:

 content = [line.rstrip('\n') for line in open('name_data.txt')] names = [] limit = 4 fp = open("name_data.txt") names.append(content[0]) for i, line in enumerate(fp): if i == limit: names.append(line) limit += 5 fp.close() print(names) 

Checkout http://shortcode.pro/code/read-txt-file-and-print-first-and-every-5th-line/

0
source

You can use regular expressions - the Python module for this is re .

Then with name_data.txt will be:

 name: Kelo family name: Lam location: Asia members: Kelo, Kiko, Jil name: Miko family name: Naiton location: Japan members: Miko,Kayati 

Getting names is a simple one-line:

 import re def get_names(): with open('name_data.txt', 'r') as f: print(re.findall(r'^name:\s*(\w+)', f.read(), flags=re.MULTILINE)) if __name__ == '__main__': get_names() 

Pay attention to the multi-line flag setting - when the parameter is global, the regular expression will also match the lines with family name: ... See Regex interactively here .

0
source

Source: https://habr.com/ru/post/1013064/


All Articles