簡體   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