【问题标题】:Open files and store contents in variable打开文件并将内容存储在变量中
【发布时间】:2020-08-12 15:21:17
【问题描述】:

代码:

import secrets 
import sys
import time
import string
from tenacity import (retry , stop_after_attempt)

#Required Defs
var = open('conf.txt','r+')
content = var.read()
print(content)

def get_random_string(length):
    letters = string.ascii_lowercase
    num = string.ascii_uppercase
    punc = string.punctuation
    spec = string.hexdigits
    one = str(num) + str(punc) + str(spec) 
    result_str = ''.join(secrets.choice(one) for i in range(length))
    print("Random string of length", length, "is:", result_str)

#Closing All Defs Here
@retry(stop=stop_after_attempt(5))
def start():
    pasw = input("Do YOu Want A Random Password: y/n: ")
    if pasw == 'y':
        leng = input("Please Type The Length Of The Password You Want: ")
        try:
            len1 = int(leng)
            get_random_string(len1)
            time.sleep(4)
        except ValueError:
            print("Only Numbers Accepted")
            time.sleep(4)
    elif pasw == 'n':
        sys.exit("You Don't Want TO Run The Program")
        time.sleep(3)
    else:
        raise Exception("Choose Only From 'y' or 'n'")

start()

问题:

我想读取名为conf.txt 的文件的内容并希望包含 只有 2 个字符 3 个字母,它基于 conf.txt。我怎样才能实现 这个?请告诉conf.txt包含:

minspec = 1 #This tells take 2 special chars chars
minnumbers = 3 #This tells take 3 Numbers
minletter = 2 #This tells take 2 lower chars
minhex = 2 #This tells take 2 hex numbers

【问题讨论】:

  • 这是作业吗?

标签: python python-3.x


【解决方案1】:
with open('file.txt', 'r') as data:
    contents = data.read()

在上面的例子中,我们使用对象名称数据以读取模式打开 file.txt。 我们可以使用 data.read() 读取文件并将其存储在变量名内容中。 使用with 的好处之一是我们不需要关闭文件,它会自动为您关闭文件。

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
  • 好的@MarkRotteveel
  • 问题已解决,感谢帮助
【解决方案2】:

对于仅读取文件对象的选定字节,可以使用:

  • seek 方法(改变文件对象的位置);
  • read 方法具有可选参数 - 要读取的字节数。

示例:

f = open('workfile', 'rb')  # b'0123456789'
f.read(2)  # reading only the first two bytes(b'01')
f.seek(6)  # go to the 6th byte in the file
f.read(3)  # reading 3 bytes after 6 position(b'678')

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多