Find entries of one text file in another file in python(在python中的另一个文件中查找一个文本文件的条目)
问题描述
我有两个文件.文件 A 的每一行都有一些条目,我需要查找文件 B 中是否有任何条目.这是我的脚本(使用两个函数):
I have two files. File A has some entries in each line and I need to find if any entry is found in File B. Here is my script (using two functions):
def readB(x):
with open('B.txt') as resultFile:
for line in resultFile:
if x in line:
print x
def readA():
with open('A.txt') as bondNumberFile:
for line in bondNumberFile:
readB(line)
readA()
此脚本在第二个文件中找到第一个条目,然后找不到下一个.这里可能有什么问题?
This script finds the first entry in second file and then does not finds the next one. What might be wrong here?
文件 A 如下所示:
122323
812549
232335
921020
文件 B 看起来像这样:
and File B looks like this:
696798 727832 750478 784201 812549 838916 870906 890988 921020
697506 727874 751037 784955 813096 838978 872494 891368 921789
696798 727832 750478 784201 812549 838916 870906 890988 921020
697506 727874 751037 784955 813096 838978 872494 891368 921789
推荐答案
去除换行符
Python 在您读取行时包含换行符 - 您的第一个条目被读取为 1223232
.去掉换行符就可以了.
Strip the entries of newlines
Python includes newlines when you read lines - your first entry is read as 1223232
. Strip the newline and it will work.
def readA():
with open('A.txt') as bondNumberFile:
for line in bondNumberFile:
readB(line.rstrip())
这篇关于在python中的另一个文件中查找一个文本文件的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在python中的另一个文件中查找一个文本文件的条目


基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01