简体   繁体   English

如何让 python 只读取文本文件的内容一次

[英]How to get python to only read the contents of a text file once

I am trying to figure out how to get Python to only read the contents of a.txt file once.我想弄清楚如何让 Python 只读取 a.txt 文件的内容一次。 It is for a class project to encrypt and decrypt a message using all printable ASCII characters.它适用于 class 项目,用于使用所有可打印的 ASCII 字符加密和解密消息。 Doing it this way is not required.不需要这样做。 This is only my fourth program I have written in Python and I really don't know what I am doing but I enjoy trying to come up with different ways to approach assignments.这只是我在 Python 中编写的第四个程序,我真的不知道自己在做什么,但我喜欢尝试提出不同的方法来处理作业。 I hope I have entered everything correctly on here.我希望我在这里正确输入了所有内容。 I know this an easy fix, I just haven't been able to find the answer.我知道这是一个简单的解决方法,我只是无法找到答案。 The assignment will be an ongoing project for the next 6 weeks.该任务将是未来 6 周的一个持续项目。 My plan is to make the encryption much more complex (yes I know that you should never use Python for encryption).我的计划是使加密更加复杂(是的,我知道您永远不应该使用 Python 进行加密)。 So I am writing it with a bigger picture in mind.所以我在写它时会考虑更大的图景。

That being said.话虽如此。 If anyone wants to go beyond answering my question, feel free to tear the entire thing apart.如果有人想 go 除了回答我的问题,请随时将整个事情拆开。 Let me know what I've done wrong, why, how I could do it better.让我知道我做错了什么,为什么,我怎样才能做得更好。 I would love to get some feedback.我很想得到一些反馈。

import random
print("1. Encrypt")
print("2. Decrypt")
print(" ")

selection = int(input("What would you like to do? [1,2]? "))

while selection == 1:
    plainText = input('Enter the message you wish to encrypt: ')

    # right now the program encrypts the string at random between 1 and 95.  
    # All of the printable ASCII characters.
    # the code below is written for when I can take the parameters of 1-95
    # off and any input will simply loop around.
    distance = random.randint(1, 95)
    if distance < 1 or distance > 95:
        print('Try Again')
        continue
    else:

        # saves the random integer or (key) 
        # directly to a file without the user seeing it.

        f = open('..\\Desktop\\encryptPractice\\theKey.txt', 'w+')

        for key in range(1):
            number = distance
            f.write(str(number))

        f.close()

        code = ""

        for ch in plainText:
            ordvalue = ord(ch)
            ordvalue = ordvalue + distance

            while ordvalue < 32:
                ordvalue += 95
            while ordvalue > 126:
                ordvalue -= 95

            code += chr(ordvalue)

            # saves the encrypted message 
            # directly to a file without the user seeing it.

        f = open('..\\Desktop\\encryptPractice\\theMessage.txt', 'w+')

        for theMessage in range(1):
            secret = code
            f.write(str(secret))
        f.close()

        print('Your message has been saved to the file named theMessage.txt')
        break


# This is the decryption block - OPTION 
# 2.)*********************************************

while selection == 2:

    """
    I want to simply be able to open the file with the 'encrypted'
    message on it and then open the file with the 'key' on it and
    have the program decrypt the message and save it back to the
    same file.

    Both of the solutions below cause the program to read the
    'encrypted' message over and over and over and...you get it.
    """

    f = open('..Desktop\\encryptPractice\\theMessage.txt','r')
    for line in f:
        print(line)


    f = open('..Desktop\\encryptPractice\\theMessage.txt','r')
    while True:
        line = f.readline()
        if line == ""
            break
        print(line)

It's hard to understand your code because it's not indented properly.很难理解您的代码,因为它没有正确缩进。 But here's my guess: the lines while selection == 1: and while selection == 2: make the block of code run in a loop until the value of selection changes.但这是我的猜测: while selection == 1:while selection == 2:代码块循环运行,直到selection的值发生变化。 If think you are looking for if selection == 1: and if selection == 2: .如果认为您正在寻找if selection == 1:if selection == 2:

Now a couple other comments about the code you shared:现在还有一些关于您共享的代码的其他评论:

  • It's impossible for distance to be less than 1 or more than 95 because randint(1, 95) returns an integer in the range [1, 95]. distance不可能小于 1 或大于 95,因为randint(1, 95)在 [1, 95] 范围内返回 integer。
distance = random.randint(1, 95)
if distance < 1 or distance > 95:                                   
    print('Try Again')                                              
    continue
  • You are using a for loop that iterates over a sequence of size 1 ( range(1) ):您正在使用一个迭代大小为 1 ( range(1) ) 的序列的for循环:
for theMessage in range(1):
    secret = code
    f.write(str(secret))

This block can be reduced to f.write(str(code))这个块可以简化为f.write(str(code))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python读取文本文件并检查其内容 - How to read a text file and check against its contents with python 将文本文件的内容读入 Python 中的字典 - Read contents of a text file into a Dictionary in Python 如何在Sublime Text 3 Python API中获取文件的内容 - How to get contents of file in Sublime Text 3 Python API 如何使用 Python read() 一次性读取大文件 - How to read large file at once with Python read() 我正在尝试从其他目录读取python中文本文件的内容-找不到文件错误 - I'm trying to read contents of text file in python from a different directory - get file not found error 如何读取文件的内容并将其转换为python中的字典 - how to read the contents of file and convert it into dictionary in python Python:如何读取多个文件夹中的所有文本文件内容并将其保存到一个excel文件中 - Python: How to read all text file contents in multiple folders and save them into one excel file 如何擦除Python中文本文件的文件内容? - How to erase the file contents of text file in Python? 是否可以在 Python 脚本中使用 read_text() 获取变量的内容? - Is it possible to get the contents of a variable with read_text() in Python script? 从python第二行读取文本文件内容 - Read a text file contents from second line in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM