Har*_*nes 9 python floating-point file
我想从一个文件中读取一个数字列表,一次只能查询一个字符,以检查该字符是什么,无论是数字,句号,+或 - ,e还是E,还是其他一些字符. ..然后根据它执行我想要的任何操作.如何使用我已有的现有代码执行此操作?这是我尝试过的一个例子,但没有用.我是python的新手.提前致谢!
import sys
def is_float(n):
state = 0
src = ""
ch = n
if state == 0:
if ch.isdigit():
src += ch
state = 1
...
f = open("file.data", 'r')
for n in f:
sys.stdout.write("%12.8e\n" % is_float(n))
Run Code Online (Sandbox Code Playgroud)
Ray*_*ger 52
这是一种制作一个一个字符的文件迭代器的技术:
from functools import partial
with open("file.data") as f:
for char in iter(partial(f.read, 1), ''):
# now do something interesting with the characters
...
Run Code Online (Sandbox Code Playgroud)
f.read(1)
. for x in open()
从文件中读取行。将整个文件作为文本块读取,然后遍历文本的每个字符:
import sys
def is_float(n):
state = 0
src = ""
ch = n
if state == 0:
if ch.isdigit():
src += ch
state = 1
...
data = open("file.data", 'r').read()
for n in data: # characters
sys.stdout.write("%12.8e\n" % is_float(n))
Run Code Online (Sandbox Code Playgroud)