[英]How to print out the file name and line number of the test in python nose?
[英]How to test line by line in a file in Python?
我有一个包含由 8 位数字组成的数字的文件。
我必须阅读每一行,如果数字不是长度为 8 位的数字并且包含字母,我必须在其旁边打印“无效”。
这是我读取文件的代码,但我不知道如何在每个数字旁边打印条件,我将不胜感激。
fname = "Data.txt"
count = 0
with open(fname, "r") as f:
for line in f:
count += 1
print("Antal Studentenommers:", count)
myfile = open("Data.txt")
for line in myfile:
print(line.strip())
myfile.close()
你的意思是以下吗?
fname = "Data.txt"
with open(fname) as myfile:
for line in myfile: # Iterate over each line in file fname
line = line.rstrip() # remove trailing '\n'
if not line.isdigit() or len(line) != 8: # check only digits and length equals 8
print(f'{line} Invalid')
测试
文件数据.txt
12345678
123456
abc12345
Output
123456 Invalid
abc12345 Invalid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.