【发布时间】:2019-06-13 19:40:01
【问题描述】:
如何打印读取数字列表中小数位和空格的输出文件。如果逗号和数字之间的小数位数多于或少于 2 位和/或空格,则该数字无效并打印在输出文本文件中。如果它有 2 个小数位并且数字和逗号之间没有空格,那么它是一个有效数字,并且 I 将打印在输出文本文件中。 输出文件: VALID #只有当float有两位小数且没有空格时才有效 10.34,456.78
INVALID #仅当浮点数大于或小于两位小数或整数或数字和逗号之间有空格时才无效 10.345, 45.678(空白,有 3 个 sig figs)
创建一个以逗号分隔的数字文件 文本文件:
1,2.12,3.123
1,1.00
有多少数字通过了 VALID sigfig 过滤器。
from functools import reduce
res = 0
outfile = "output2.txt"
baconFile = open(outfile,"wt")
index = 0
invalid_string = "INVALID"
valid_string = "VALID"
for line in open("file.txt"): #for loop with variable line defined and using open() function to open the file inside the directory
for line in open("file.txt"): #for loop with variable line defined and using open() function to open the file inside the directory
carrera = ''
index = index +1 #adds 1 for every line if it finds what the command wants
print("Line {}: ".format(index))
baconFile.write("Line {}: ".format(index))
with open('file.txt') as file:
number_list = file.readline().strip().split(',')
for line in number_list:
if len(line.split('.')[-1]) == 2:
#res += 1
## print("VALID")
carrera = valid_string
if len(line.split('.')[-1]) != 2:
#res += 1
carrera = invalid_string
print (carrera)
baconFile.write(carrera + " ")
#print(res)
baconFile.close()
#For example, my list looks like this from my text file:
1,2.12,3.123
#Then it print out this to my output text file
output (decimal places from each number):
Line 1: INVALID VALID INVALID
#However, if my list from my text file is like this:
1,2.12,3.123
1,1.00
#Then it print out this to my output text file
output:
Line 1: Line 2: INVALID
VALID
INVALID
Line 3: Line 4: INVALID
VALID
INVALID
#How do I get it to print out like this to my output text file:
Line 1: INVALID VALID INVALID
LINE 2: INVALID VALID
【问题讨论】:
标签: python python-3.x