python - 打开文件并将内容存储在变量中
问题描述
代码:
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()
在上面的示例中,我们使用对象名称数据以读取模式打开 file.txt。我们可以使用 data.read() 读取文件并将其存储在变量名内容中。使用的好处之一with
是我们不需要关闭文件,它会自动为您关闭文件。
推荐阅读
- node.js - 在firebase云功能中,孩子正在自我删除
- android - PokeGenie 是如何工作的?它从哪里获取数据?(口袋妖怪GO)
- google-bigquery - BigQuery x Python:如何使用 dbapi 游标将 GEOGRAPHY 插入表中?
- python - 带间隔的滚动平均值
- java - GoogleMap、CameraPosition 以北为目标坐标
- excel - 使用 do while 循环时,我的 VBA 代码不起作用
- rest - 如何从嵌套的 HTTP 客户端访问密钥?
- r - 错误:geom_path:每个组仅包含一个观察值
- android - 如何从另一个类访问函数 - Flutter
- angular - 表单字段以 Angular 中的“必需”错误启动