【发布时间】:2021-10-02 22:39:09
【问题描述】:
我创建了一个空文本文件,并在其中保存了一些内容。这是我保存的:
Saish ddd TestUser ForTestUse
这些词之前有一个空格。无论如何,我想知道如何使用 python 在文本文件中只读取 1 个 WORD。这是我使用的代码:
#Uncommenting the line below the line does literally nothing.
import time
#import mmap, re
print("Loading Data...")
time.sleep(2)
with open("User_Data.txt") as f:
lines = f.read() ##Assume the sample file has 3 lines
first = lines.split(None, 1)[0]
print(first)
print("Type user number 1 - 4 for using different user.")
ans = input('Is the name above correct?(y/1 - 4) ')
if ans == 'y':
print("Ok! You will be called", first)
elif ans == '1':
print("You are already registered to", first)
elif ans == '2':
print('Switching to accounts...')
time.sleep(0.5)
with open("User_Data.txt") as f:
lines = f.read() ##Assume the sample file has 3 lines
second = lines.split(None, 2)[2]
print(second)
#Fix the passord issue! Very important as this is SECURITY!!!
当我运行代码时,我的输出是:
Loading Data...
Saish
Type user number 1 - 4 for using different user.
Is the name above correct?(y/1 - 4) 2
Switching to accounts...
TestUser ForTestUse
如您所见,它同时显示“TestUser”和“ForTestUse”,而我只希望它显示“TestUser”。
【问题讨论】:
-
和你只读一行一样:你读more超过一行,然后忽略多余的。 (严格来说,
readline()并没有完全丢弃多余的内容——它只是将它放在缓冲区中,以便以后用户要求阅读更多内容时使用——但要点是一样的:你不能要求操作系统读取一个单词或一行,因此您需要一次读取一个字节,直到到达单词分隔符或行分隔符,或者只读取更大的块并仅关注您实际关心的子集)。
标签: python linux raspberry-pi text-files