首页 > 解决方案 > 如何在 python 中只读取 1 个单词?

问题描述

我创建了一个空文本文件,并在其中保存了一些内容。这是我保存的:

 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”。

标签: pythonlinuxraspberry-pitext-files

解决方案


当你给 一个限制时split(),从那个限制到结束的所有项目都被组合起来。所以如果你这样做

lines = 'Saish ddd TestUser ForTestUse'
split = lines.split(None, 2)

结果是

['Saish', 'ddd', 'TestUser ForTestUse']

如果您只想要第三个单词,请不要限制split().

second = lines.split()[2]

推荐阅读