用大写字母写?

时间:2012-01-08 14:33:08

标签: python file sequences

我有下一个代码:

    bestand = open("6_frame.txt", "r")
    seq = bestand.readlines()
    #to make a list
    for line in seq:
        alle = line
        while True: 
            if alle.isupper():
                break
            else:
                print ("try again ")

使用这段代码我想确保在文件中写序列的人用大写字母写这个序列,并且想要除了其他错误:但他想做我想做的事。

有人能帮助我吗?

3 个答案:

答案 0 :(得分:3)

我认为你说要确保整个文件都是大写的。如果这就是你要找的东西,那就可以了:

if all(x.isupper() for x in open("6_frame.txt", "r")):
    print("entire file is upper-case.")
else:
    print("try again!")

这将测试所有大写字符的文件,一次一行。如果找到的行不是,则返回false,否则如果所有行都是大写,则返回true(并打印“整个文件大写”)。

更新(文件观看版)

看起来你想继续检查文件,直到它全部为大写。这是一种相当低效的方法(您可以添加模态检查,或使用inotify使其更好):

from time import sleep

while True:
    lines = open("6_frame.txt", "r")
    if all((x.isupper() or x.isspace()) for x in lines):
        print("entire file is upper-case.")
        break  # We're done watching file, exit loop
    else:
        print("try again!")

    sleep(1)   # Wait for user to correct file

此外,当您的脚本再次检查文件时,如果此人处于中间保存,您可能会遇到异常(我不确定),因此您可能需要在all行周围添加一些异常。无论哪种方式......希望这有帮助!

答案 1 :(得分:0)

我的abc.txt内容为aBC,所以不是全部大写:

fd = open('abc.txt','r')
seq = fd.readlines()
for line in seq:
       if line.isupper():
                  print('all capital')
       else:
                print('try again')

因此我的输出= try again

如果我的abc.txt内容为ABC,则我的输出为all capital

答案 2 :(得分:0)

确定文件中的所有外壳字符是否为大写,否则重试:

import time
from hashlib import md5

hprev = None
while True:
    with open("6_frame.txt") as f:
         text = f.read()
         if text.isupper():
            print('all capital')
            break
         else:
            h = md5(text).hexdigest()
            if h != hprev: # print message if the file changed
               print('try again')
            hprev = h
            time.sleep(1) # wait for the file to change
相关问题