Hi,so I am supposed to encrypt a text file chosen by a user at the moment I have completed most of it (offset factor/shift), I have got each separate character from the text file and put it into a list and converted it into ASCII, I am wondering how you are meant to change the ASCII number 32(space) into an actual space to separate the list and only them. Then i will need to create a string based on this and save it onto the user's computer and i am not too sure how to do this either.
Any help/advice will be appreciated
Thanks very much!
Here is the code:

import random
#=============================================Main Menu=============================================
print("Hi, Welcome to Text Encyrption")
print("This program will encrypt or decrypt a text file chosen by you.") 
print('Make a choice')
print('1. Encrypt Message')
print('2. Decrypt Message ')
print('3. Exit program ')
print()
#the user only has 3 choices
menu_choice = 0
#menu_choice cannot = 3
while menu_choice != 3:
    menu_choice = int(input("Choose an option (1-3): "))
#=====================================Encryption=======================================================
    if menu_choice == 1:
        print("ENCRYPTING MESSAGE")
        print("For this task the file is Text File1.txt")
        text_file = input(str("Enter the file you want to be Encyrpted"))
#this will find the text file the user has inputter
        apple = open(text_file,"r")
#this puts the text file so it can only be read
        apple =(apple.read())
        print(apple)
        n = 0
        number = []
        texting = []
#================================Offset Factor=================================================== 
#while n is less than 8
        while n<8:
#it will convert a random number between 33 and 126 into ascii
            random_number = chr(random.randint(33, 126))
            print(random_number)
#every time n + 1
#one turn out of 8
            n = n + 1
#the number is put into ascii
            characters = ord(random_number)
#it is put into the number list
            number.append(characters)
        print(number)
#this rounds each of the eight integers in number and divides by 8 and takes away 3
        offset_number = round((number[0]+number[1]+number[2]+number[3]+number[4]+number[5]+number[7])/8)-32
#this prints the offset factor
        print(offset_number)
#=============================Task 5=====================================================================
        newString = []
#this is the only part of ascii allowed
        validLetters = "#$%&'()*+,-./:;<=>?@[\]^_`{|}~""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghiklmnopqrstuvwxyz{|}~"
        space = [' ']
        new = []
        old = []
        x = 0
#this splits the text file into singukar characters from 0 to 1
        chrsplit = [apple[i:i+1] for i in range(0, len(apple),1)]
#this puts into ascii every character
        ascii_conversion = [ord(a) for a in chrsplit]
#this replaces each 32 in the list with a space
        ascii_conversion = [s.replace('32', ' ') for s in ascii_conversion]
#this prints it
        print(ascii_conversion)

I don't think you actually would want to treat the spaces (or whitespace in general) any differently from the other plaintext, actually; you want to write the ciphertext out in a form that gives as little information as possible to a cryptanalyst, so enciphering the whitespace would make more sense. You don't want to store or write the ciphertext out as a string at all, but as a binary in your cipher.

Okay thanks, although my course work days if it is a space then it should not be encrypted. It's GCSE so it is rather basic although I understand where you are coming from, the course work wants the cipher text to be saved onto the computer.
Many thanks!

Ah, I didn't realize that was an actual requirement of the assignment. Sorry.

One thing I will strongly recommend is reorganizing the program into functions, so that it is easier to read, and less redundant. Here is what I came up with (though it doesn't take into account the spaces issue):

from random import randint
from statistics import mean

def generate_key():
    """ generate a key for the enciphered message"""
    numbers = list()
    # while n is less than 8
    for n in range(8):
        # generate eight random numbers between 33 and 126
        partial_seed = randint(33, 126)
        numbers.append(partial_seed)
        # this averages and rounds the values in numbers
        # and then subtracts 32
        avg = round(mean(numbers))
        return avg - 32

def apply_cipher(plaintext, cipher_key):
    return [(ord(chars) ^ cipher_key) for chars in plaintext]

def apply_deciphering(ciphertext, cipher_key):
    plaindata =  [chr(values ^ cipher_key) for values in ciphertext]
    return ''.join(plaindata)

def encrypt(source, dest):
    """ encrypt the given file """
    cipher_key = generate_key()
    with open(source) as plaintext_file:
        with open(dest, "wb") as ciphertext_file:
            ciphertext_file.write(bytes(chr(cipher_key), 'utf-8'))
            ciphertext = apply_cipher(plaintext_file.read(), cipher_key)
            ciphertext_file.write(bytes(ciphertext))

def decrypt(source, dest):
    with open(source, "rb") as ciphertext_file:
        ciphertext = ciphertext_file.read()
        cipher_key = ciphertext[0]
        plaintext = apply_deciphering(ciphertext[1:], cipher_key)
        with open(dest, "w") as plaintext_file:
            plaintext_file.write(plaintext)


def print_menu():
    menu = ['Display main menu', 'Encrypt Message', 'Decrypt Message', 'Exit program']
    for opt_number, option in enumerate(menu):
        print('{0}) {1}'.format(opt_number, option))

if __name__ == "__main__":
    print("Hi, Welcome to Text Encryption")
    print("This program will encrypt or decrypt a text file chosen by you.")
    print_menu()

    #the user only has 4 choices
    menu_choice = 0

    #menu_choice == 3 ends the program
    while menu_choice != 3:
        try:
            menu_choice = int(input("Choose an option (0-3): "))
            if 0 > menu_choice > 3:
                print('Please select a value from 1 to 3.')
        except ValueError:
            print("The selected option must be an integer.")

        if menu_choice == 0:
            print_menu()
        elif menu_choice == 1:
            plaintext_file = input("Enter the file you want to be encrypted: ")
            ciphertext_file = input("Enter the file to write the encrypted message out to: ")
            encrypt(plaintext_file, ciphertext_file)

        elif menu_choice == 2:
            ciphertext_file = input("Enter the file you want to be decrypted: ")
            plaintext_file = input("Enter the file to write the decrypted message out to: ")
            decrypt(ciphertext_file, plaintext_file)

While it probably doesn't work quie the way your assignment is meant to, it is a working program, and should give you a starting point for refactoring your program. Let me know if there are any parts you are confused by.

Thanks a lot, really helpful should be able to work my way back to involve spaces but that's great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.