python-3.x - 在文本文件Python中编辑密码的最简单方法

标签 python-3.x csv edit

我有以下代码,它经历了逐行读取文件、将其转换为列表、编辑该列表中的字段的阶段,但最后一个阶段是重写原始文件,包括此编辑。

我对建议最简单/最简单的修复(不使用 pandas/numpy 等)并使用提供的原始代码的答案感兴趣。

我当前的算法包括必须创建一个包含所有记录(链接到该用户名的记录除外)的新文件,然后写入此列表。这看起来很困难而且没有必要。非常感谢任何解决方案!

评论中对该任务的解释更清楚:

代码

 """ ==============TASK
    ALLOW THE USER TO CHANGE OR EDIT THEIR PASSWORD
    1. Search for any given username
    2. Edit the password field for that given username
    3. Save the new updated username and password to file / updated
    """

    import csv
    def main():
        #1. This code snippet asks the user for a username and then allows them to change password for that record
        updatedlist=[]
        with open("fakefacebook.txt",newline="") as f:
          reader=csv.reader(f)
          print("CHANGE PASSWORD?!")
          username=input("Enter the username for the required user:")
          for row in reader: #for every row in the file
              for field in row:

                    if field==username: #if a field is == to the required username
                        updatedlist.append(row) #add each row, line by line, into a list called 'udpatedlist'
                        newpassword=input("Enter new password")
                        #print(updatedlist[0][1]) (this is how we get at the password field, noting it is a nested list)
                        updatedlist[0][1] = newpassword #set the field for password to the new password


          updatepassword(updatedlist)

    def updatepassword(updatedlist):
        with open("fakefacebook.txt","w",newline="") as f:
            Writer=csv.writer(f)
            Writer.writerows(updatedlist)
            print("File has been updated")


    main()

注意:目前代码仅允许用户更改密码(并且在列表中更改)。该列表仅包含该用户的记录。它将这条记录(使用更改后的密码)覆盖到文本文件,而不是所需的内容(原始文件内容+仅此编辑)

文件内容

username,password,email,no_of_likes
marvR,pass123,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c9c5d6d2e4c3c9c5cdc88ac7cbc9" rel="noreferrer noopener nofollow">[email protected]</a>,400
smithC,open123,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d0d2c1c7f3d4ded2dadf9dd0dcde" rel="noreferrer noopener nofollow">[email protected]</a>,200
blogsJ,2bg123,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7416181b13341319151d185a171b19" rel="noreferrer noopener nofollow">[email protected]</a>,99

所需输出

如果使用:marvR 进行测试 更改密码为:boo123

新文件应包含:

username,password,email,no_of_likes
marvR,**boo123**,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="630e02111523040e020a0f4d000c0e" rel="noreferrer noopener nofollow">[email protected]</a>,400
smithC,open123,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a393b282e1a3d373b333674393537" rel="noreferrer noopener nofollow">[email protected]</a>,200
blogsJ,2bg123,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5d5350587f58525e5653115c5052" rel="noreferrer noopener nofollow">[email protected]</a>,99

任何有关初学者教学的最佳方法的评论/解释也将不胜感激。奇怪的是,Python 没有开发某种模块来使编辑文件中的字段比这个 3 步算法更容易,这对于初学者(我说的是 13-14 岁的 child )来说确实相当困难

最佳答案

到目前为止,其中一个相关问题尚未得到解决。您提到了“教学初学者”,因此请将此答案视为其他答案的补充。

当编辑密码文件等文件时,不应像此处提供的代码一样覆盖原始文件。如果由于任何原因(包括磁盘已满或断电)写入失败,则可能会丢失数据。更重要的是,文件应该始终处于一致的状态,即没有人应该看到部分写入的文件。

要实现这一点:

  1. 从文件中读取数据
  2. 在内存中修改它根据需要处理数据
  3. 将结果保存到新的临时文件,关闭该文件(with 自动执行),您甚至可能想要调用 os.fsync()
  4. 如果出现任何错误,请删除临时文件并在此停止
  5. 只有在一切正常的情况下,最好使用 os.replace() (Python 3.3+) 自动将临时文件重命名为原始文件。原子操作一步完成。

更新:修改了 updatepassword 代码并添加了一些注释:

FILE = "fakefacebook.txt"

def updatepassword(updatedlist):
    # create the tempfile in the same directory (os.replace requires the same filesystem)
    tempfile = FILE + ".tmp"
    try:
        # "x" = fail with the FileExistsError if the file exists already
        with open(tempfile, "x", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(updatedlist)
            f.flush()               # flush the internal buffers
            os.fsync(f.fileno())    # write to disk
        os.replace(tempfile, FILE)
        print("File has been updated")
        tempfile = None     # tempfile renamed
    except FileExistsError:
        print("Another copy is running or stale tempfile exists")
        tempfile = None     # tempfile does not belong to this process
    except OSError as err:
        print("Error: {}".format(err))
    finally:
        if tempfile:
            try:
                os.unlink(tempfile)
            except OSError:
                print("Could not delete the tempfile")

关于python-3.x - 在文本文件Python中编辑密码的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308593/

相关文章:

python-3.x - 使用 python 定义类构造函数

python - 将新列添加到可变长度的数据框中

csv - 替换或删除所有\n 但不\r\n

python - 如何使用 Pandas 将多个 csv 文件中的单个数据列合并为一个?

javascript - 强制浏览器从 url 下载 CSV 文件

Python 3.2 UnicodeEncodeError

python-3.x - 如何将数据从 Azure ML(笔记本)传输到存储容器

javascript - jqgrid 在编辑框中不正确选择下拉选项值

javascript - 如何在 Odoo 中的 JavaScript 上扩展此功能(编辑按钮)?

C- 编辑/更新文件(不一定在最后)。 fopen(路径, "a+")不起作用