Python write line number

How to print line numbers of a file in Python?

EasyTweaks.com

Use the Python enumerate function to loop through a text or csv file and then, for each line print the line number and the line values. Here’s a simple snippet:

with open (your_file_path, 'r') as f: for i, line in enumerate (f): print(f'Line number:; Content: '.strip()) 

Create an Example file

Assuming that you have the following multi-line text written into a text file in your operating system (either Windows, Linux or macOS)

This is our log file.
It is located at the C:\MyWork directory.
This file was built with Python.

Find the line numbers and print the line contents

Our task is to print for each line of the file the line number and the line contents.

# import the path library - ships from Python 3.4 and onwards from pathlib import Path # replace with path of file in your environment file_path = Path('C:\WorkDir\multi_line_file.txt') # Verify that file exists if file_path.is_file(): #Open file and loop through lines, print line number and content with open (file_path, 'r') as f: for i, line in enumerate (f): print(f'Line number:; Content: '.strip()) else: print("The file doesn't exist.")

This will return the following result:

Line number:1; Content: This is our log file. Line number:2; Content: It is located at the C:\MyWork directory. Line number:3; Content: This file was built with Python.

Next we would like to search for a specific string in the file contents and print only the specific line which contains the string. We will use the re (regular expressions) module to easily parse the file.

 with open (file_path, 'r') as f: for i, line in enumerate (f): # search for words ending with the string 'thon' if (re.search(r'thon\b', line)): print(f'Line number:; Content: '.strip()) 

This will render the following result:

Line number:3; Content: This file was built with Python.

Get number of lines in a Python file

To count the number of lines in a text file with Python, proceed as following:

file_path = Path('C:\WorkDir\multi_line_file.txt') with open (file_path, 'r') as f: for l in file: l += 1 print (f'The file line count is : ') 

Источник

Simple, efficient way to writing to a specific line number in python

Unless the new line is exactly as long as the old line, you best option would be to rewrite the file, anyway.

The easiest way to do so is to use the fileinput module:

import sys, fileinput for count, line in enumerate(fileinput.input(filename, inplace=True)): if count == 69: # Python counts from 0 line = newvalue sys.stdout.write(line) 

This creates a backup of the file, and output goes to a new file replacing the old. Writing to sys.stdout writes to than new file (the alternative is to use print but line still includes the newline).

In the special case where your lines are always the same length you can use

with open('myfile.txt', 'rb+') as f: f.seek(FIXED_LINE_LENGTH * line_number) f.write(new_line) 
  • Python — Most efficient way to find how often each possible pair of words occurs in the same line in a text file?
  • The most efficient way to find the point where maximum number of intervals overlap with python
  • What is the most efficient way to choose from a list of variables and generate a number combination that falls between a specific range with python?
  • Deleting n number of lines after specific line of file in python
  • I’m looking for a simple way to generate code in python
  • Truncate a string to a specific number of bytes in Python
  • Need more efficient way to parse out csv file in Python
  • Random number with specific variance in Python
  • Is there a more efficient way to convert this phone number to plain text?
  • Most computationally efficient way to build a Python list with repeating and iterating numbers like [0, 0, 0, 1, 1, 1, 2, 2, 2 . . . ,etc]
  • Efficient way of removing keys of certain prefix from python dictionary
  • Most efficient way of comparing the contents of two class instances in python
  • Python append lists in a specific way
  • Fastest & I/O efficient way to combine heterogeneous CSV files in Python
  • Efficient way in Python to add an element to a comma-separated string
  • What is the fastest way to represent number as the sum of powers of two in python
  • Why is this simple python program not working the way I want it to?
  • How to reorganize a list in specific way in Python
  • What is the most efficient way to repeatedly use regular expressions in a Python loop?
  • Most clean and efficient way to generate and zip two lists in Python
  • what is the most efficient way of concat two numbers to one number in python?
  • Writing files in python the correct way
  • Writing variables to new line of txt file in python
  • python — efficient way of checking if part of string is in the list
  • Efficient way of counting number of elements smaller (larger) than cutoff in a sorted list
  • Find a more efficient way to code an If statement in python
  • In Python 3, what is the most efficient way to change the values in a list?
  • Is there a simple way to handle key doesn’t exist in python for loop?
  • More efficient way to write this small bit of Python code?
  • Efficient and accurate way to compact and compare Python lists?
  • Pythonic way of writing a long line of code
  • I need to arrange my list in a specific way — python
  • Python — print() — debugging -show file and line number
  • How to limit the number of times a specific random number is generated python
  • Get line number python from opened file
  • Python — Any way of checking if number 0 or False
  • More efficient way to delete list item with index Python
  • Prepend line number to string in python
  • Efficient way in Python to remove an element from a comma-separated string
  • Python most efficient way to keep sorted data
  • Concise way to create new dictionary with specific property as key, from list of dictionaries in Python
  • Catch a specific `Windows Error` number — python
  • Find specific words in text file and print the line using Python
  • Counting the number of specific characters ignoring duplicates: Python
  • Efficient way to manipualte specific part of an object inside of a list
  • Printing out each line (from file) with line number python
  • Generating numbers in python loop with specific number
  • Simple Way of NOT reading last N lines of a file in Python
  • Way to match number patterns in Python
  • Efficient Python way to process two huge files?

More Query from same tag

  • How can I fix cudart64_110.dll error which caused from Tensorflow in Pycharm?
  • How to format list output in python
  • Python mock attributes defined and set within __init__
  • pythonic way to flip a list/tuple
  • How to know how many data points Matplotlib is using for a scatterplot
  • Nested for-while loop stops iteration after first run
  • Strange «symbolic boolean expression has no truth value» error — is it a bug in SymPy?
  • Remove sub-string from beginning of string
  • @reboot cronjob not executing
  • Zero results in Query/GqlQuery
  • How can I draw a cross which follows my mouse cursor?
  • Python : How to import a module if I have its path as a string?
  • word separator for python coding
  • python slice set in list
  • How to test to see if a top-level window is open?
  • Why does splinter is_text_present() cause intermittent StaleElementReferenceException with Firefox (but not Chrome or phantomjs)?
  • Why is `self.__x` not working but `self.y` is?
  • How to delete a point in influxDB
  • How can I get my user agent header in a simple way using requests in python 2.7?
  • asyncio: unable to create new event loop
  • Python way to append text to the same string
  • ARIMA forecast gives different results with new python statsmodels
  • Call a particular python class using User input
  • Bees with Machine Guns syntax error involving paramiko. (self._close(async=True))
  • Call a method after all instance method calls in a class automatically: a metaclass or a decorator?
  • Extracting Sequences from Multiple Strings
  • Updating python version on a Mac
  • Play 2 sounds simultaneously with multiprocessing in python
  • Matching specific table within HTML, BeautifulSoup
  • Python remove same characters from a list
  • always point to other attribute’s function
  • How to write file name to use URL name in python?
  • Reading file from the same directory as the python module
  • Speed comparison between bisect.insort function and list.index and insert function
  • How to include lagged variables in statsmodel ols regression

Источник

Get the Filename and a Line Number in Python

Get the Filename and a Line Number in Python

When working on real-world applications or side projects, we often have to retrieve line numbers and filenames for debugging purposes. Generally, this is done to understand what code is getting executed when or to analyse the flow of control of any application. In this article, we will learn how to get a line number and the filename of the Python script using Python.

Get the Filename and a Line Number in Python

To get the filename and a line number from the executing Python script, we can use the inspect module Python. The inspect module contains several utilities to fetch information about objects, classes, methods, functions, frame objects, and code objects. This library has a getframeinfo() method that retrieves information about a frame or a traceback object. This method accepts a frame argument about which it retrieves details. The currentFrame() method returns the frame object for the caller’s stack frame. We can use these utilities for our use case. Refer to the following Python code to understand the usage.

from inspect import currentframe, getframeinfo  frame = getframeinfo(currentframe()) filename = frame.filename line = frame.lineno print("Filename:", filename) print("Line Number:", line) 
Filename: full/path/to/file/main.py Line Number: 3 

As we can see, the filename attribute will return the full path to the Python file. In my case, the Python file’s name was main.py ; hence, it shows main.py in the output. And, the lineno attribute return the line number at which this frame = getframeinfo(currentframe()) statement was executed. The mentioned statement was execute at line 3 ; hence the output has a 3 after the Line Number label.

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article — Python File

Источник

Читайте также:  jQuery css() Demo
Оцените статью