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
How to Share Single Sqlite Connection in Multi-Threaded Python Application
Most Efficient Way to Construct Similarity Matrix
How to Further Filter a Result of Resultset
How to Find the Maximum Consecutive Occurrences of a Number in Python
How to Populate New Column Based on Values in Other Columns
How to Drop Rows of Pandas Dataframe Whose Value in a Certain Column Is Nan
Calculate Rgb Value for a Range of Values to Create Heat Map
Compare Two Lists and Find the Unique Values
Conda: Remove All Installed Packages from Base/Root Environment
How to Print Numbers in a List That Are Less Than a Variable. Python
How to Enable Autocomplete (Intellisense) for Python Package Modules
Is There a Short-Hand for Nth Root of X in Python
Why Am I Getting Ioerror: [Errno 13] Permission Denied
Open() Gives Filenotfounderror/Ioerror: Errno 2 No Such File or Directory
Python Data Frame How to Find the Local Maximum in a 2D Array