python print first n lines of string
If you only want to get the 10 first elements of the list then just slice the list accordingly
for word, numbers in enumerate(sorted[:10]):
print(word,':',numbers)
How to print the first n lines of file?
Literally, read first n lines, then stop.
def read_first_lines(filename, limit):
result = []
with open(filename, 'r') as input_file:
# files are iterable, you can have a for-loop over a file.
for line_number, line in enumerate(input_file):
if line_number > limit: # line_number starts at 0.
break
result.append(line)
return result
Python how to get last N lines of a multiline string
str.splitlines()
with a simple slice:
mstr.splitlines()[-n:]
The solution above will return these lines as a list. If you want a string, you also need to use str.join()
:
'\n'.join(mstr.splitlines()[-n:])
If your text doesn't contain it, you might also want to add the last newline, if you're catenating it with other text, or writing it to a file on UNIX-like OS:
'\n'.join(mstr.splitlines()[-n:]) + '\n'
How to read first N lines of a file?
Python 3:
with open("datafile") as myfile:
head = [next(myfile) for x in range(N)]
print(head)
Python 2:
with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head
Here's another way (both Python 2 & 3):
from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print(head)
How to print the first N lines of a file in python with N as argument
Arguments are available via the sys
package.
Example 1: ./file.py datafile 10
#!/usr/bin/env python3
import sys
myfile = sys.argv[1]
N = int(sys.argv[2])
with open("datafile") as myfile:
head = myfile.readlines()[0:args.N]
print(head)
Example 2: ./file.py datafile --N 10
If you want to pass multiple optional arguments you should have a look at the argparse package.
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description='Read head of file.')
parser.add_argument('file', help='Textfile to read')
parser.add_argument('--N', type=int, default=10, help='Number of lines to read')
args = parser.parse_args()
with open(args.file) as myfile:
head = myfile.readlines()[0:args.N]
print(head)
How to read first N lines of a text file and write it to another text file?
Well, you have it right, using islice(filename, n)
will get you the first n
lines of file filename
. The problem here is when you try and write these lines to another file.
The error is pretty intuitive (I've added the full error one receives in this case):
TypeError: write() argument must be str, not list
This is because f.write()
accepts strings as parameters, not list
types.
So, instead of dumping the list as is, write the contents of it in your other file using a for
loop:
with open("input.txt", "r") as myfile:
head = list(islice(myfile, 3))
# always remember, use files in a with statement
with open("output.txt", "w") as f2:
for item in head:
f2.write(item)
Granted that the contents of the list are all of type str
this works like a charm; if not, you just need to wrap each item
in the for
loop in an str()
call to make sure it is converted to a string.
If you want an approach that doesn't require a loop, you could always consider using f.writelines()
instead of f.write()
(and, take a look at Jon's comment for another tip with writelines
).
Get first character of each line from string with multiple lines in Python
Try
data = """
Come to the
River
Of my
Soulful
Sentiments
Meandering silently
Yearning for release.
Hasten
Earnestly
As my love flows by
Rushing through the flood-gates
To your heart.
"""
# Get each line into a list by splitting data on every newline
# ['', 'Come to the', 'River', 'Of my', ... 'To your heart.', '']
data_list = data.split("\n")
# Get a list of the first letter of every list element
# use only those elements with length > 0
# ['C', 'R', 'O', 'S', 'S', 'M', 'Y', 'H', 'E', 'A', 'R', 'T']
letters_list = [x[0] for x in data_list if len(x)>0]
# Join it to make one word
# 'CROSSMYHEART'
my_word = ''.join(letters_list)
# Capitalise only the first letter
my_word = my_word.capitalize()
# Print out the answer.
# 'Crossmyheart'
print(my_word)
Related Topics
Efficiently Find Repeated Characters in a String
How to Normalize a 2-Dimensional Numpy Array in Python Less Verbose
Most Efficient Way to Find Mode in Numpy Array
Get Span Inside a Class Using Webdriver and Selenium
Pandas Open_Excel() Fails With Xlrd.Biffh.Xlrderror: Can't Find Workbook in Ole2 Compound Document
Sum of Square Differences (Ssd) in Numpy/Scipy
Pip Install Not Working With Jenkins
How to Open Excel File Fast in Python
Conda: Remove All Installed Packages from Base/Root Environment
Subtracting Values Across Grouped Data Frames in Pandas
How to Automatically Download Files from a Pop Up Dialog Using Selenium-Python
Navigating Through Pagination With Selenium in Python
Check If List Is Ascending or Descending (Using For)
How to Force Pip to Reinstall the Current Version
Get Absolute Paths of All Files in a Directory
Arrange a Text File Using Python
Pandas: Calculate the Percentage Between Two Rows and Add the Value as a Column