[英]In python, how can I search a specific column for a specific value in a txt file then return the specific value's row?
First of all, I have recently started studying python. 首先,我最近开始研究python。 So I am a beginner.
所以我是一个初学者。
1111 1 3
1112 1 2
1113 2 3
1114 1 7
1115 7 2
Assume I have these values in the text file. 假设我在文本文件中有这些值。 As in the title, I want to search a specific column for a specific value in the txt file then return the specific value's row except for the searched "value".
就像标题中一样,我想在txt文件中的特定列中搜索特定值,然后返回特定值的行(搜索到的“值”除外)。
Example: 例:
Search the first column for 1113
value. 在第一列中搜索
1113
值。
Then return 2 3
as: 然后返回
2 3
为:
x = 2
y = 3
You could try this: 您可以尝试以下方法:
import sys
with open( filename, "r" ) as f:
for line in f:
parts = line.split(" ")
if parts[0] == "1113":
print("x={0} y={1}".format( parts[1], parts[2] ))
sys.exit(0)
Try something like this: 尝试这样的事情:
with open('file.txt', 'r') as f:
for line in f:
if line.startswith('1113'):
line = line.split()
x = int(line[1])
y = int(line[2])
as 'file.txt'
put your file name and as '1113'
put the value you are looking for. 如
'file.txt'
您的文件名,如'1113'
输入您要查找的值。 good luck 祝好运
There is a csv module which will do all the dirty work for you: 有一个csv模块可以为您完成所有肮脏的工作:
import csv
def find(filename, number):
with open(filename) as file:
reader = csv.DictReader(file,
fieldnames=['col1', 'col2', 'col3'],
delimiter=' ')
for line in reader:
if line['col1'] == str(number):
return (line['col2'], line['col3'])
if __name__ == '__main__':
(x, y) = find('data.txt', 1113) or (None, None)
print(x, y)
I'd prefer: 我更喜欢:
search_text = '1113'
with open(FileName) as f:
for i in f:
if i.strip() != '':
for j in i.strip().split():
if j[0] == search_text:
x = int(i[1])
y = int(i[2])
This will allow you to search for any value on any column. 这将允许您在任何列上搜索任何值。
import csv
def find(reader, col, val):
for row in reader:
if row[col] == val:
return row
raise ValueError('Value {} not found in row {}'.format(val, col))
def findexcept(reader, col, val):
r = find(reader, col, val)
r.pop(col)
return r
with open('searchdata.txt') as f:
lines = (line.strip() for line in f)
c = csv.reader(lines, delimiter=' ', skipinitialspace=True)
try:
x = findexcept(c, 0, '1114')
print(x)
except ValueError as ve:
print('Error: {}'.format(ve))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.