文本文件中的搜索和排序

2024-10-02 20:41:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是相当新的代码,我有一个问题,在阅读文本文件。 对于我的代码,我需要要求用户键入一个特定的名称代码,以便继续执行代码。但是,用户可以使用不同的名称代码,我不知道如何制作,因此如果您键入其中一个代码,您可以继续。你知道吗

例如,文本文件如下所示

约翰123,x,x,x

苏珊233,x,x,x

康纳,x,x,x

我需要做的是接受这个名字标签,不管它是什么,并能够打印它之后。所有的名称标签都在一列中。你知道吗

file = open("paintingjobs.txt","r")

details = file.readlines()


for line in details:
    estimatenum = input ("Please enter the estimate number.")
    if estimatenum = line.split

到目前为止,这是我的代码,但是我不知道该怎么做来查看name标记是否有效,以允许用户继续。你知道吗


Tags: 代码用户txt名称键入line标签open
2条回答

这里是另一个解决方案,没有pickle。我假设您的凭证每行存储一个。如果没有,你需要告诉我他们是怎么分开的。你知道吗

name = 'John'
code = '1234'

with open('file.txt', 'r') as file:
    possible_match = [line.replace(name, '') for line in file if name in line]

authenticated = False

for item in possible_match:
    if code in tmp: # Or, e.g. int(code) == int(tmp) 
        authenticated = True
        break

您可以使用名为pickle的模块。这是一个python3.0内部库。在Python2.0中,它被称为:cPickle;在这两种语言中,其他所有内容都是相同的。你知道吗

请注意,你这样做不是一个安全的方法!你知道吗

from pickle import dump

credentials = {
    'John': 1234,
    'James': 4321,
    'Julie': 6789
}


dump(credentials, open("credentials.p", "wb"))

这将保存一个名为credentials.p的文件。您可以按如下方式加载:

from pickle import load

credentials = load(open("credentials.p", "rb"))

print(credentials)

以下是一些测试:

test_name = 'John'
test_code = 1234

这相当于:

print('Test: ', credentials[test_name] == test_code)

显示:{'John': 1234, 'James': 4321, 'Julie': 6789}

显示:Test: True

test_code = 2343
print('Test:', credentials[test_name] == test_code)

显示:Test: False

相关问题 更多 >