如何从具有字节格式数据的文件中读取字符串?

如何解决如何从具有字节格式数据的文件中读取字符串?

我正在从Flask开发CRUD应用程序。它根据用户输入随机生成许多密码。用户还可以将输入保存在CSV文件中,然后在终端上打印输出。

这是源代码

exec_prog.py (用于创建Web界面)

from Password_creator import *
from flask import Flask,render_template,request,redirect,url_for
from csv import *
from table import Table
from flask_modus import Modus
from werkzeug import secure_filename
from cryptography.fernet import Fernet

app = Flask(__name__,template_folder='template')
modus= Modus(app)


@app.route("/")
def data_input(): # for user input for suggestions
    return render_template('input.html')


@app.route('/data-extract') # for extracting the user input
def data_extract():
    global sug
    sug = int(request.args.get('sug')) # to get the user input
    return redirect('/generate/new') # redirecting to generate



@app.route('/generate/new') # for generating the passwords
def generate():
    global final_g
    global data_x
    global password
    final_g = [] # for the passwords
    password = []
    for i in range(sug):
     v =  password_generator("","","") #for calling the class
     alpha_g = v.alpha_rand_func()    # line 25- 30; please refer the Password_creator.py file                 
     sym_g = v.symbol_rand_func()
     int_g = v.int_rand_func()
     spec_g = v.special_number_production()     
     final = v.final_output 
     final_g.append(v.final_output)
     passwd_obj = Table(v.final_output,'nil') # for storing them in a class 
     password.append(passwd_obj) # for storing them in a list
    return redirect('/generate/show-output')


@app.route('/generate/show-output',methods  = ["GET","POST"])
def show_output():    
    return render_template('output_disp.html',final_lst = password) # rendering the output_disp.html


@app.route('/generate/<int:id>',methods = ["GET","PATCH","POST"]) # for modifying the function
def show(id):
     found  =  next(entry for entry in password if entry.id == id) # for finding the entry with the required id
     if request.method  == b"PATCH": # for dealing with PATCH 
        found.passwd = request.form['edit_passwd']
        found.desc = request.form['description']
        return redirect('/generate/show-output')
     return render_template('modify.html',found_entry = found)

@app.route('/generate/file-manip-disp') # for displaying the uploading and downloadng options for password
def disp_manip_menu():
  return render_template('file-manip.html')

@app.route('/generate/file-manip',"POST"]) # for uploading the passwords
def save_file():
  pass_output_lst = [] #for passwords
  desc_output_lst = [] #for descriptions of the password
  encrypted_pass_output_lst = [] #storing passwords after encryption
  encrypted_desc_output_lst = [] #storing descriptions of passwords after encryption
  
  if request.method == "POST": # checking if the request method is POST
    pass_file = request.files['fileName'] #requesting the name of the password saving file
    pass_file_Name = secure_filename(pass_file.filename) #storing the name of the password saving file
    key = Fernet.generate_key() # generating a key
    key_init = Fernet(key)  # storing the key for encrypting purpose
    key_file = request.files['keyfile']  # requesting the key saving file
    key_file_name = secure_filename(key_file.filename) #storing the name of the key saving file
    for i in password:
      encrypted_pass_output_lst.append(key_init.encrypt(bytes(i.passwd,encoding = "utf-8")))  #line 79 -80: storing the passwords and descriptions
      encrypted_desc_output_lst.append(key_init.encrypt(bytes(i.desc,encoding  = "utf-8")))   #by converting them into bytes and then encrypting them
    with open(pass_file_Name,"w") as k: #for writing the password and description in the required file
      writer_param = writer(k,delimiter=":",quoting = QUOTE_NONE,quotechar=" ") #csv writer
      for i in range(sug):
        writer_param.writerow([encrypted_pass_output_lst[i],encrypted_pass_output_lst[i]]) # writing the contents of the list
    with open(key_file_name,"wb") as k: # for writing the key in the required file
      k.write(key)
    return render_template("file-manip.html",message = "file saved succesfully") 
@app.route('/generate/file-manip-upload',"POST"])

def upload_file(): #for uploading the file
  encrypted_pass_output_lst = []
  encrypted_desc_output_lst = []
  Upload_key = "" #for storing the key
  if request.method == "POST":
    Uploadfile= request.files['Uploadfile'] #requesting the name of the required file
    Uploadfile_req = secure_filename(Uploadfile.filename) #storing the name of the password saving file
    Uploadkeyfile = request.files['Uploadkeyfile'] #requesting the name of the key storing file
    Uploadkeyfile_req = secure_filename(Uploadkeyfile.filename) #storing the name of the key storing file
    with open(Uploadkeyfile_req,"rb") as k: #for reading the data of the key storing file and storing it in  Upload_key
      Upload_key = k.read()
    Upload_key_init = Fernet(Upload_key) # for storing the key for decrypting purpose
    with open(Uploadfile_req,"rb") as k: # opening the password-storing file
      reader_param =  reader(k,quoting=QUOTE_NONE,quotechar=" ") #csv reader
      for arr in reader_param:
        encrypted_pass_output_lst.append( Upload_key_init.decrypt(arr[0]) ) #line 105-106: storing the passwords and descriptions in the 
        encrypted_desc_output_lst.append( Upload_key_init.decrypt(arr[1]) ) #respective variables by decrypting them first
        print(encrypted_pass_output_lst,encrypted_desc_output_lst) #printing the lists

      
  return render_template('file-manip.html',message = "file uplaoded succesfully")
     

Password_creator.py (用于生成密码)

from random import *
from itertools import *
import string
class password_generator():  
   def __init__(self,final_output,special_nproduction,final_specp): #creating the local variables
       self.final_output = final_output
       self.special_nproduction = special_nproduction
       self.final_specp = final_specp
      
      
   def alpha_rand_func(self): #for randomly selecting alphabets
       alpha = string.ascii_letters
       for i in range(4):
           self.final_output += choice(alpha)
        
   def symbol_rand_func(self): #for randomly selecting symbols
      symbol = string.punctuation
      for i in range(3):
         self.special_nproduction += choice(symbol)
             
   def int_rand_func(self): #for randomly selecting integers
      integer = string.digits
      for i in range(2):
         self.special_nproduction += choice(integer)
        
   def special_number_production(self): #for concatenating the integers and symbols
          self.special_nproduction = list(self.special_nproduction)
          init_perm = list(permutations((self.special_nproduction),5))
          selected_comb_init_list = choice(init_perm) #selecting a permutation of integers and symbols randomly
          mod_selected_comb_init = "" #for storing the permutation in the form of a variable
          for i in selected_comb_init_list: #iterating through the selected_comb_init_list
             mod_selected_comb_init += i 
          self.final_output += mod_selected_comb_init  # adding the integer-symbol combination to final output
   def final_output_production(self): #for concatenating all the characters,selecting a combination of it randommly and returning it as output
           return self.final_output #returns the final output
####################################          

####################################

table.py (用于存储生成的密码)

class Table(): #class for storing the passwords with their description
    count  = 1
    def __init__(self,passwd,desc):
        self.passwd = passwd
        self.desc = desc
        self.id = Table.count
        Table.count += 1

str_main.html (基本html文件)

<!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css">
    </head>
    <body>
        {%block content%}
        {%endblock%}
    </body>
</html>

input.html (用于用户输入)

{%extends 'str_main.html'%}
{% block content %}
<div id  = "suggest-input">
    <form action  = "/data-extract" method = "GET">
      <input type ="number" placeholder="no. of suggestions",name="sug">
      <input type= "submit",value = "click here">
    </form>
</div>
{% endblock %}

output_disp.html (用于显示所需的输出)

{% extends 'str_main.html'%}
    {% block content%}
    <div id  =  "options">
      <div id  = "btn-output-1"><h6>Upload file</h6></div>
      <div id  = "btn-output-2"><a href="{{url_for('data_input')}}"><h6>Home</h6></a></div>
      <div id  = "btn-output-3"><a href ="{{url_for('disp_manip_menu')}}"><h6>Save</h6></a></div> 
    </div>
    <div id = "output-head">
      <h1>Here are the suggestions</h1>
    </div>
    <div id  = "output-div">  
      <form id = "output-data" method = "POST" enctype = "multipart/form-data">   
        <table>
             <tr>
               <th>Password</th>
               <th>Description</th>
             </tr>
             
             {% for i in final_lst %}
            <tr>    
               <td> <a href ="{{url_for('show',id  = i.id)}}">{{ i.passwd }}</a></td> 
               <td>{{ i.desc }}</td>
            </tr>     
             {% endfor %}
        </table>
        
      </form>
    </div>   

{% endblock %}

modify.html (用于修改生成的密码)

{% extends 'str_main.html' %}
{% block content %}
<div id  = "modify-div">
<form id = "edit" action = "{{url_for('show',id  = found_entry.id)}}?_method=PATCH" method ="POST">
   <input type = "text" value = "{{found_entry.passwd}}" name = "edit_passwd">
   <input type = "text" value  ="{{found_entry.desc}}" name = "description">
   <input type ="submit" value = "save change" >
</form>
</div>
{% endblock %}

file-manip.html (用于文件操作)

{% extends 'str_main.html' %}
{% block content %}
<p>Saving file</p>
<form method= "POST" action = "/generate/file-manip" enctype = "multipart/form-data">
    <label>For the password storing file</label>
    <input type = "file" value = "browse" name = "fileName">
    <label>For the file storing the key</label>
    <input type = "file" value = "key file" name = "keyfile">
    <input type ="submit" value= "saving file">

</form>
<p>Uploading file</p>
<form method= "POST" action = "/generate/file-manip-upload" enctype = "multipart/form-data">
  <label>For the password storing file</label>
  <input type = "file" value = "browse" name = "Uploadfile">
  <input type = "file" value = "key file" name = "Uploadkeyfile">
  <input type ="submit" value= "saving file">


</form>
<br/>
<p>{{message}}</p>

{% endblock %}

当我在终端中选择了用于打印密码的所需文件时,出现以下错误。

    for arr in reader_param:
_csv.Error: iterator should return strings,not bytes (did you open the file in text mode?)

我试图在代码的必需部分中更改读写模式,但是没有任何效果。因此,我想知道是什么导致了此错误,以及如何解决该问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-