如何解决打开文件并将内容存储在变量中
代码:
t1(s)
问题:
我想读取名为t1(s)
的文件的内容,并希望包含
仅2个字符3个字母,它基于#x(t),y(t),z(t)
#Generic
import numpy as np
import math
from scipy.integrate import quad
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
#FIRST SET OF PARAMETERS R_01=3.5
epsilon1=1/10**6
beta1=0.25
gamma1=0.071
R_01 = float(int(10*beta1/gamma1))/10
print(R_01)
def f1(x):
return 1/(-x*gamma1*np.log(x) - beta1*(1-epsilon1)*x**2 + beta1)#Integrand
def t1(s):
return quad(f1,s,1)#Integral with s as independent variable
def h1(x):
return gamma1 * np.log(x) / beta1 - (1 - epsilon1) * x + 1#Function where the root s_fin1 is to be found
s_fin1 = fsolve(h1,0.004)
t_fin1 = t1(s_fin1)
t_fin1=int(100*(t_fin1[0]))/100
print(t_fin1)
plt.show()
。我该如何实现
这个?请告诉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
解决方法
with open('file.txt','r') as data:
contents = data.read()
在上面的示例中,我们以对象名称数据的读取模式打开file.txt。
我们可以使用data.read()读取文件并将其存储在变量名内容中。
使用with
的优点之一是我们不需要关闭文件,它会自动为您关闭文件。
只能读取文件对象的选定字节:
- 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')