繁体   English   中英

如果 txt 文件的行以另一个 txt 文件中的数字开头 python

[英]if lines of txt file start with numbers in another txt file python

with open('D:\Scripting Test/Full Data.txt') as f:
 for line in f:
   with open('D:\Scripting Test/Numbers.txt') as ff:
     for linee in ff:
       if line.startswith(linee):
           print(line)

我想打印文件(full-data.txt)中的所有行,如果它们以文件(numbers.txt)中的任何数字开头

完整数据.txt:

4/0/0        
3/0/7        
4/0/7        
4/0/3        
4/0/4        
4/0/1        
3/0/5        
3/0/1        
2/0/5        
2/0/3        
2/0/4        
2/0/6        
3/0/2        
1/0/3        
6/0/6        
6/0/12       
1/0/5        
1/0/4        
3/0/4        

数字.txt:

1 

2 

5 

8

output 应该是:

2/0/5        
2/0/3        
2/0/4        
2/0/6

1/0/3

1/0/5        
1/0/4

您的问题是,当您阅读某些数字时,它们包含空格,例如换行符和空格。 因此,首先尝试将所有数字读入一个数组并去除所有空格:

nums = []
with open('D:\\Scripting Test\\Numbers.txt') as f:
    nums = f.read().split('\n')
    nums = [n.strip() for n in nums if n != ''] # strip whitespace and get rid of empty lines

with open('D:\\Scripting Test\\Full Data.txt') as f:
    for line in f:
        for num in nums:
            if line.startswith(num):
                print(line)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM