Better Way to Extract Only 2Nd Column of a Txt File in Python

Extract only desired columns from a txt file using Python?

Not sure what your traceback is, but I would recommend using the following:

with open('newfile', 'rw') as newfile:
lines = newfile.readlines()
for row in lines:
x = row.strip().split()
if len(x) >= 2:
print(x[0].ljust(4) + ' ' + x[1])

This will avoid possible issues with malformed lines causing IndexError exceptions from popping-up. Also, ljust(4) gives the output nicer formatting by left-justifying the string in the VLAN column with four spaces.

How to get one column of a text file

This is one way of getting the values, using regex

import re

# Extract the details present inside "|(26.7)c" and convert to float.
with open("numaralar.txt") as f:
# "re.findall" extracts all the values that match the pattern
vals = [float(x) for x in re.findall("\|(.*)c", f.read())]
# vals = [25.1, 25.1, 25.2, 25.3]

# Use in-built function to get the required values.
print("Min:", min(vals))
print("Max:", max(vals))
print("Avg:", sum(vals)/len(vals))

Extracting specific columns from a file to create new file in python

Try this:

for line in dta_2path:
if line.strip():
cols = line.split()
ws_2.write(cols[1] + "\t" + cols[5] + "\n")


Related Topics



Leave a reply



Submit