如何从Python中的文本文件中提取用户输入

时间:2017-11-06 21:41:46

标签: python text-files user-input

所以我有一个文本文件,应该在整个Python脚本中用作用户输入。假设我的文本文件如下所示:

[a-zA-Z]+_[a-zA-Z]+_[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])

然后我有一个看起来像这样的while循环:

input1
input2
input3
input4

如何循环输入文本文件,将每一行作为字符串,并将该字符串用作while循环内的用户输入?

由于

3 个答案:

答案 0 :(得分:0)

在问这个问题之前你应该环顾四周。您只需使用func receiptValidation() { let SUBSCRIPTION_SECRET = "yourpasswordift" let receiptPath = Bundle.main.appStoreReceiptURL?.path if FileManager.default.fileExists(atPath: receiptPath!){ var receiptData:NSData? do{ receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped) } catch{ print("ERROR: " + error.localizedDescription) } //let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn) print(base64encodedReceipt!) let requestDictionary = ["receipt-data":base64encodedReceipt!,"password":SUBSCRIPTION_SECRET] guard JSONSerialization.isValidJSONObject(requestDictionary) else { print("requestDictionary is not valid JSON"); return } do { let requestData = try JSONSerialization.data(withJSONObject: requestDictionary) let validationURLString = "https://sandbox.itunes.apple.com/verifyReceipt" // this works but as noted above it's best to use your own trusted server guard let validationURL = URL(string: validationURLString) else { print("the validation url could not be created, unlikely error"); return } let session = URLSession(configuration: URLSessionConfiguration.default) var request = URLRequest(url: validationURL) request.httpMethod = "POST" request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData let task = session.uploadTask(with: request, from: requestData) { (data, response, error) in if let data = data , error == nil { do { let appReceiptJSON = try JSONSerialization.jsonObject(with: data) print("success. here is the json representation of the app receipt: \(appReceiptJSON)") // if you are using your server this will be a json representation of whatever your server provided } catch let error as NSError { print("json serialization failed with error: \(error)") } } else { print("the upload task returned an error: \(error)") } } task.resume() } catch let error as NSError { print("json serialization failed with error: \(error)") } } } 即可。 Python: read all text file lines in loop

答案 1 :(得分:0)

我建议使用fileinput模块(https://docs.python.org/2/library/fileinput.html)代替,但值得一提的是,您可以将输入管道输入到希望从用户读取的程序中,例如:

bash-3.2$ cat prog.py 
#!/usr/bin/env python

while True:
    try:
        x = raw_input()
    except EOFError:
        break
    if x == "a":
        print 'got a'
    elif x == 'b':
        print 'such b'
    else:
        print 'meh %r' % x
bash-3.2$ cat vals.txt 
a
b
c
bash-3.2$ # equivalent to: cat vals.txt | ./prog.py
bash-3.2$ ./prog.py < vals.txt
got a
such b
meh 'c'

答案 2 :(得分:0)

您所寻找的内容听起来像是经典的生成器解决方案(有关详情,请阅读pep 255):

def function1():
    print("function1")

def function2():
    print("function2")

def function3():
    print("function3")

def choose_input(the_input):
    return {
        'input1': function1,
        'input2': function2,
        'input3': function3
    }[the_input]


with open("file.txt") as file:
    inputs = (choose_input(i.rstrip("\n")) for i in file.readlines())

[my_input_function_call() for my_input_function_call in inputs]