簡體   English   中英

打開文件並將內容存儲在變量中

[英]Open files and store contents in variable

代碼:

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
with open('file.txt', 'r') as data:
    contents = data.read()

在上面的示例中,我們使用 object 名稱數據以讀取模式打開 file.txt。 我們可以使用 data.read() 讀取文件並將其存儲在變量名內容中。 使用with的好處之一是我們不需要關閉文件,它會自動為您關閉文件。

對於僅讀取文件 object 的選定字節,可以使用:

  • 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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM