如何从Python中的文件一次读取一个字符? [英] How to read in one character at a time from a file in python?

查看:321
本文介绍了如何从Python中的文件一次读取一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个文件中读取一个数字列表作为字符,每次一个字符,以检查字符是什么,不管是数字,句号,+还是 - ,e或E或某些其他字符...然后执行任何我想要的操作基于此。我怎样才能使用现有的代码来做到这一点?这是我尝试过的一个例子,但没有奏效。我是python的新手。

pre $


$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $


$ b $ = 0
src =
ch = n
if state == 0:
如果ch.isdigit():
src + = ch
state = 1
...

f = open(file.data,'r')
for f:
sys.stdout.write( %12.8e\\\
%is_float(n))


解决方案

<在open()中的x> 从文件中读取行。阅读文件中的整个文件,然后浏览文本的每个字符:

  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 data in data:#characters
sys.stdout.write(%12.8e\\\
%is_float(n))


I want to read in a list of numbers from a file as chars one char at a time to check what that char is, whether it is a digit, a period, a + or -, an e or E, or some other char...and then perform whatever operation I want based on that. How can I do this using the existing code I already have? This is an example that I have tried, but didn't work. I am new to python. Thanks in advance!

    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))

解决方案

for x in open() reads lines from a file. Read the entire file in as a block of text, then go through each character of the text:

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))

这篇关于如何从Python中的文件一次读取一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆