Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 文本文件中的搜索和排序_Python_File_Python 3.x_Text - Fatal编程技术网

Python 文本文件中的搜索和排序

Python 文本文件中的搜索和排序,python,file,python-3.x,text,Python,File,Python 3.x,Text,我对代码相当陌生,在阅读文本文件时遇到问题。 对于我的代码,我需要要求用户输入一个特定的名称代码,以便继续代码。但是,用户可以使用不同的名称代码,我不知道如何使用,因此如果您键入其中一个代码,您可以继续 例如,文本文件如下所示 约翰123,x,x,x 苏珊233,x,x,x 康纳,x,x,x 我需要做的是接受名称标签,不管它是什么,然后能够打印出来。所有名称标记都在一列中 file = open("paintingjobs.txt","r") details = file.readlines(

我对代码相当陌生,在阅读文本文件时遇到问题。 对于我的代码,我需要要求用户输入一个特定的名称代码,以便继续代码。但是,用户可以使用不同的名称代码,我不知道如何使用,因此如果您键入其中一个代码,您可以继续

例如,文本文件如下所示

约翰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标记是否有效以允许用户继续

您可以使用名为
pickle
的模块。这是一个Python 3.0内部库。在Python 2.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
这里是另一个解决方案,没有
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
带到这里面呢?恐怕我真的不能使用任何导入,我希望找到一个没有任何导入的解决方案。非常感谢你的帮助!简单化的方法。做他们想做的事最简单的方法。Python的内部库。以与保存数据相同的结构打开数据,即在本例中是一个
dict
。不清楚您在这里尝试执行的操作。预期的输出是什么?在给定用户输入的情况下,您能给出一个具体的预期输出示例吗?无论如何,要检查文本文件的某一行中是否存在用户输入,可以使用“if estimatenum in line:”。