简体   繁体   English

使用 Python 验证保存的文本文件以检查是否设置了参数

[英]Validating saved text file with Python to check if parameters are set

I've got a problem with validating text file.我在验证文本文件时遇到问题。 I need to check if parameters that I set are correctly saved.我需要检查我设置的参数是否正确保存。 File name is an actual date and time and I need to check if parameters that were send are in this text (log) file.文件名是实际日期和时间,我需要检查发送的参数是否在此文本(日志)文件中。 Below you can find my code:您可以在下面找到我的代码:

Arguments are sent with argpars eg. Arguments 与 argpars 一起发送,例如。 parser.add_argument("freq", type=int) parser.add_argument(“频率”,类型=int)


print('Saving Measurement...')
print(inst.write(':MMEMory:STORe:TRACe 0, "%s"' % timestr)) #Saving file on the inst

time.sleep(1) #Wait for file to save
print('Downloading file from device...')
ftp = FTP('XX.XX.XXX.XXX') 
ftp.login()
ftp.retrbinary('RETR %s'% timestr + '.spa', open(timestr + '.spa', 'wb').write) #downloading saved file into a directory where you run script

print('Done, saved as: ' + timestr)
time.sleep(1)

with open (timestr + '.spa') as f:
    if (str(args.freq)) in f.read():
        print("saved correctly")

ftp.delete(timestr + '.spa') #Delete file from inst
ftp.quit()

I'm not sure if it works for me.我不确定它是否适合我。 Thank you for your help谢谢您的帮助

You could use the re module to help you find a date pattern inside your file.您可以使用re module来帮助您在文件中找到日期模式。 I will give you a little example code that searches, at least for this case, this date pattern dd-mm-yyyy我会给你一个小的示例代码,至少在这种情况下,搜索这个日期模式 dd-mm-yyyy

import re

filepath = 'your-file-path.spa'
regex = '\d\d-\d\d-\d\d\d\d'

with open(filepath, 'r') as f:
    file = f.read()

dates_found = re.findall(regex, file)
# dates_found will be an array with all the dates found in the file
print(dates_found)

You could use any regex you want as the first argument of re.findall(regex, file)您可以使用任何您想要的正则表达式作为re.findall(regex, file)的第一个参数

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

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