Reading Strings and outputting them to a console Different (Python) - python

Sorry for the Title not sure how to word this.
What i am trying to do is make a code that can be only written and read using my program I have already made it so i can write code out to a file, But i am unsure how to make it be read without changing the text file i only want my code to print out to the console or idle without changing the text file at all, I am not asking you to write out the code for me but just how to go about doing this?
print ("Welcome Who am i speaking too?")
User = input("Name: ")
print ("Welcome " +User)
Running = True
def FileReader():
FileName = input("Please Enter File Name: ")
file = open (FileName + ".txt" , "r")
#How Do i go about this?
print (file.read())
file.close()
def FileOutput():
NameOfFile = input("Enter File Name: ")
File = open(NameOfFile + ".txt", "wt")
Content = input("Type Your Message: ")
Content = Content.replace(" ", "SP")
Content = Content.replace("a", "ASDAFAS")
Content = Content.replace("b", "ASDAKSGDHLHASJD")
Content = Content.replace("c", "ASHJDGASGDKJASG")
Content = Content.replace("d", "JHASGDHASLASHGD")
Content = Content.replace("e", "AKJ:SBDKJASBDASJDBSDBKL")
Content = Content.replace("f", "KBASLLASIBDJBASLDJ")
Content = Content.replace("g", "ASJHDVBLKAJSDBLASJDB")
Content = Content.replace("h", "JHAKSDHKDKSAJDHASJKSHDA")
Content = Content.replace("i", "KJABSDJKABSDKJBASKJDBASKJDB")
Content = Content.replace("j", ":AJSDJASDJKAHSDJHSD")
Content = Content.replace("k", "OAHISDIUHASIDASDHD")
Content = Content.replace("l", "UIAHSDUIHSADIUSHADUIYSA")
Content = Content.replace("m", "ASHDUASHDUHASUDHUIASDHIUHA")
Content = Content.replace("n", "IUAHSDIUHASIDUIAUSHDHUIS")
Content = Content.replace("o", "AHJSVDJHSVABDJHVSD")
Content = Content.replace("p", "IASDIJASIDJAISDJOIAJSD")
Content = Content.replace("q", "LIUAGSDIUGWVDASID")
Content = Content.replace("r", "JAHSDJWIUCBASB")
Content = Content.replace("s", "OIAHSDBIWUBDUIB")
Content = Content.replace("t", "LAJHSBDHBWQIEUBQWIUW")
Content = Content.replace("u", "INQWOIDNWQIOND")
Content = Content.replace("v", "OIHQWEIUCBWOIQBEUWQBEWOQIEB")
Content = Content.replace("W", "OASIHDOIASDOSAHDAISDH")
Content = Content.replace("x", "OIAJDIWQDBUIOEHWQE")
Content = Content.replace("y", "POASJDPOQWEOJWQOEJWQEOP")
Content = Content.replace("z", "ASJDBSOBDOWBQDWIOD")
File.write(Content)
while Running:
What = input("What Would you like to do: ")
if What == "read":
FileReader()
if What == "write":
FileOutput()
if What == "close":
Running = False

Himal is right.
file.read()
file.close()

Related

Python program doesn't write in a file

The user gives input to the program and it should write it in a file There is a problem with uploading it to the txt file.
Plan = open("Plan.txt", "r")
content = Plan.read()
Plan_lista = content.split(",")
Przedmioty = []
Przedmioty = list(set(Plan_lista))
Przedmioty.remove("")
Plan.close()
#Dodawanie linków do listy
Linki = open("Linki.txt", "w+")
print("\n" + "Podaj Link do:")
a=0;
for i in range(len(Przedmioty)):
print (Przedmioty[a], end = "\r")
link = input(": ")
Linki.write(Przedmioty[a] + "," + link)
if ( a != len(Przedmioty)-1):
Linki.write(", ")
a+=1

4 functions near identical, one works but the others dont no errors

I have 4 functions that should grab some text from a specific docx file that are highlighted scan4<colour> is the varialbe of the text, these functions are near identical but are searching and replacing different highglighted text, they print out the same but they dont replace the text
these are 2 functions of 4, the yellow one works while the green one doesnt
what the code does is it searches and replaces the text then encrypts then uses the encrypted string into the main document, the other does the exact same but searches for a different highlighted colour. I try to encrypt the first function works but the second one doesn't
This code searches for yellow encodes the text and then replaces it so the un-encrypted document shows the encrypted string of the contents
def securi1_key():
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
global key1
key1 = file.read()
file.close()
def rewrite_yellow():
securi1_key()
save_yellow_text()
# get key from file
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
texty = scan4yellow.decode("utf-8")
encodedy = texty.encode()
# encrypt message
f = Fernet(key1)
encryptedy = f.encrypt(encodedy)
print(scan4yellow)
print(scan4yellow.decode("utf-8"))
document = docx.Document(f1)
for paragraph in document.paragraphs:
if scan4yellow.decode("utf-8") in paragraph.text:
inline = paragraph.runs
# loops for runs
for i in range(len(inline)):
if scan4yellow.decode("utf-8") in inline[i].text:
text = inline[i].text.replace(scan4yellow.decode("utf-8"), encryptedy.decode("utf-8"))
inline[i].text = text
document.save(f1)
def save_yellow_text():
securi1_key()
fp = f1
p = Path(fp)
filename1 = p.stem
storedtexty = filename1 + " Yellow Text"
storedtextencryptedy = storedtexty + ".encrypted"
list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")
if storedtexty in list_of_files:
storedtexty = (storedtexty + "1")
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty, "w+")
file.write(scan4yellow.decode("utf-8"))
input_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty)
if storedtextencryptedy in list_of_files:
storedtextencryptedy = (storedtextencryptedy + "1")
output_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedy)
with open(input_file1, "rb") as f:
data = f.read()
fernet = Fernet(key1)
encrypted = fernet.encrypt(data)
with open(output_file1, "wb") as f:
f.write(encrypted)
file.close()
os.remove(input_file1)
this code should do the exact same but for the colour green :
def securi2_key():
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
global key2
key2 = file.read()
file.close()
def rewrite_green():
securi2_key()
save_green_text()
# get key from file
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
textg = scan4green.decode("utf-8")
encodedg = textg.encode()
print(encodedg)
# encrypt message
f = Fernet(key2)
encryptedg = f.encrypt(encodedg)
print(encryptedg)
document = docx.Document(f1)
for paragraph in document.paragraphs:
if scan4green.decode("utf-8") in paragraph.text:
inline = paragraph.runs
# loops for runs
for i in range(len(inline)):
if scan4green.decode("utf-8") in inline[i].text:
text = inline[i].text.replace(scan4green.decode("utf-8"), encryptedg.decode("utf-8"))
inline[i].text = text
document.save(f1)
def save_green_text():
securi2_key()
fp = f1
p = Path(fp)
filename2 = p.stem
storedtextg = filename2 + " Green Text"
storedtextencryptedg = storedtextg + ".encrypted"
list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")
if storedtextg in list_of_files:
storedtextg = (storedtextg + "1")
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg, "w+")
file.write(scan4green.decode("utf-8"))
print(scan4green.decode("utf-8") + "tested1")
input_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg)
if storedtextencryptedg in list_of_files:
storedtextencryptedg = (storedtextencryptedg + "1")
output_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedg)
with open(input_file2, "rb") as f:
data = f.read()
fernet = Fernet(key2)
encrypted = fernet.encrypt(data)
with open(output_file2, "wb") as f:
f.write(encrypted)
file.close()
os.remove(input_file2)
I should have some incoherent string replace the actual text and the actual text saved in another file encrypted, but all this does is work for the first yellow function but not the green function
Ideally it should take the text from the read in file, make a copy write it out to a file and encrypt that then take the string of encryption from that and replace it where it was in the read in file, but it only works for the yellow code while the green and the other code which are near identical do not work
I have found an answer, what I changed has nothing to do with the code I provided but when I read in the text it was scan4green = (word.find(tag_t).text.encode('utf-8').lower()). this apparently caused it not to work properly but the scan4yellow did work because i didn't have .lower() attached to the end.

Python - List not printing to outfile

I'm trying to write a program for checking out/returning books at the library and I'm using temporary lists as storage for all the data in the patrons.txt and books.txt so I can edit it and then put it back in. The problem is that when I try to print the tempBookFile and tempPatronFile to outfile, the "file = outfile" part of following line
print(tempBookFile, file = outfile)
is highlighted in yellow and when I hover over it it says Expected type 'Optional[IO[str]] got 'TextIOWrapper[str]' instead". As a result, everything in the book list and patron list gets deleted, except for the name of the book which is stored in the patron file while it is checked out.
class Book:
def __init__(self, title, author, genre, isbn):
self.title = title
self.author = author
self.genre = genre
self.isbn = isbn
def printAll(self,outfile):
print(self.title, "|", self.author, "|", self.genre, "|", self.isbn, file = outfile)
class Patron:
def __init__(self, name, phone, books):
self.name = name
self.phone = phone
self.books = books
def printAll(self, outfile):
print(self.name, "|", self.phone, "|", self.books, file = outfile)
def main():
print("Welcome to JCK library!")
menu = eval(input("Main menu. Type 1 to enter books, 2 for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))
while(menu != 6):
if(menu == 1):
outfile = open("books.txt", "w")
title = input("Enter title: ")
while(title != "done" and title != "Done"):
author = input("Enter author: ")
genre = input("Enter genre: ")
isbn = input("Enter isbn: ")
book = Book(title,author,genre,isbn)
book.printAll(outfile)
print("Book added: ", title)
print("Author: ", author)
print("Isbn: ", isbn, "\n")
title = input("Enter title: ")
outfile.close()
menu = eval(input( "Main menu. Type 1 to enter books, 2 for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))
elif(menu == 2):
outfile = open("patrons.txt", "w")
name = input("Enter patron name: ")
phone = input("Enter phone number: ")
books = []
patron = Patron(name,phone,books)
patron.printAll(outfile)
outfile.close()
menu = eval(input("Main menu. Type 1 to enter books, 2 for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))
elif(menu == 3):
title = ""
author = ""
genre = ""
isbn = ""
name = ""
phone = ""
books = []
outfile = open("patrons.txt", "r")
patronName = input("Enter Patron Name: ")
if (patronName in outfile.read()):
print("Patron found.")
for line in outfile.readlines():
if(patronName in line):
patronInfo = line.split("|")
name = patronInfo[0]
phone = patronInfo[1]
books = patronInfo[2]
#Creates a temporary list containing all of the contents of the patrons.txt file so that
#the list can be modified and then put back into the patrons.txt file
tempPatronFile = outfile.readlines()
#Removes the line from the temporary list that contains information about the patron who is checking out
#a book so that it can be re-added to the list after it is updated
for line in tempPatronFile:
if(patronName in line):
tempPatronFile.pop(line)
outfile.close()
outfile = open("books.txt", "r")
bookName = input("Enter Book Name: ")
if bookName in outfile.read():
books.append(bookName)
for line in outfile.readlines():
if(bookName in line):
bookInfo = line.split("|")
title = bookInfo[0]
author = bookInfo[1]
genre = bookInfo[2]
isbn = bookInfo[3]
book = Book(title,author,genre,isbn)
#Creates a temporary list containing all of the contents of the books.txt file so that
#the list can be modified and then put back into the books.txt file
tempBookFile = outfile.readlines()
#Removes the line from the temporary list that contains information about the book so that
#the book can be re-added later after it has been returned.
for line in tempBookFile:
if(bookName in line):
tempBookFile.pop(line)
outfile.close()
outfile = open("books.txt", "w")
print(tempBookFile, file = outfile)
outfile.close()
outfile = open("patrons.txt", "w")
print(tempPatronFile, file = outfile)
patron = Patron(name,phone,books)
patron.printAll(outfile)
book.printAll(outfile)
outfile.close()
print("Book due in 2 weeks.")
menu = eval(input("Main menu. Type 1 to enter books, 2 for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))
elif(menu == 4):
outfile = open("patrons.txt", "r")
patronName = input("Enter patron name: ")
if(patronName in outfile.read()):
for line in outfile.readlines():
if(patronName in line):
patronInfo = line.split("|")
name = patronInfo[0]
phone = patronInfo[1]
books = patronInfo[2]
bookName = input("Enter book name: ")
if(bookName in outfile.read()):
for line in outfile.readlines():
if(bookName in line):
bookInfo = line.split("|")
title = bookInfo[0]
author = bookInfo[1]
genre = bookInfo[2]
isbn = bookInfo[3]
book = Book(title, author, genre, isbn)
# Creates a temporary list containing all of the contents of the patrons.txt file so that
# the list can be modified and then put back into the patrons.txt file
tempPatronFile = outfile.readlines()
# Removes the line from the temporary list that contains information about the patron who is checking out
# a book so that it can be re-added to the list after it is updated
for line in tempPatronFile:
if (patronName in line):
tempPatronFile.pop(line)
#Removes the information about the book which was stored in the patron file while it was checked out.
#Upon being returned, the book will go back into the books.txt file
for line in tempPatronFile:
if(bookName in line):
tempPatronFile.pop(line)
outfile.close()
outfile = open("books.txt", "r")
tempBookFile = outfile.readlines()
tempBookFile.append(book)###################################
outfile.close()
outfile = open("books.txt", "w")
print(tempBookFile, file = outfile)
outfile.close()
outfile = open("patrons.txt", "w")
for line in books:
if(bookName in line):
books.pop(line)
patron = Patron(name,phone,books)
print(tempPatronFile, file = outfile)
patron.printAll(outfile)
outfile.close()
print("Book returned.")
menu = eval(input("Main menu. Type 1 to enter books, 2 for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))
elif(menu == 5):
outfile = open("patrons.txt", "r")
patronName = input("Input patron's name: ")
if(patronName in outfile.read()):
for line in outfile.readlines():
if(patronName in line):
patronInfo = line.split("|")
name = patronInfo[0]
phone = patronInfo[1]
books = patronInfo[2]
print(patronName, "has the following book(s) checked out:\n", books)
menu = eval(input("Main menu. Type 1 to enter books, 2 for new patron, 3 to check out book, 4 return book, 5 show status, 6 exit. "))
print("Have a nice day!")
main()
The issue has to do with your old school file opening. You should avoid using open and close to manage your files and instead use a with statement. Most of the time if you are using resources that need to be cleaned up/managed you should use
with open("my_file.txt", "w") as output_file:
# File based operations here
And then PyCharm will be happy. You can see a similar problem here: PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead
Also as someone commented (it's now deleted) make sure you are opening the file in the correct mode. "w" will erase everything in the file and let you write to it. "r" will only let you read from it. "a" will let you append to the file and might be what you want. If you look up the inputs to open you can get the full details. https://docs.python.org/3/library/functions.html#open

Python replace word for line [duplicate]

def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()

Python: Using an input to determine what line to save on

I'm currently working on a task where I must store scores in a text file. This is my code thus far:
def FileHandle():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'a')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
FileHandle()
My question is, how would I check already existed names in the text file and only add their score, rather than name and score, to the line it existed on?
This is what the file looks like:
Jonathon: 1
Micky: 5
How it would look after adding a score:
Jonathon: 1, 4
Mickey: 5
# The score added here is Jonathon's 4
Attempt:
# Accept scores
name = input("Name: ")
correct = input("Number: ")
if name in grade_book.keys and "," in grade_book.keys <= 2():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
If you are entering many scores at a time, I suggest reading the file into memory and working with things there. Doing an open/close on the file for every score update is very inefficient.
# Read the file into a dictionary
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
name, scores = line.split(':')
grade_book[name] = scores.strip()
File.close()
print grade_book
# Accept scores
name = raw_input("Name: ")
while name != "":
correct = raw_input("Number: ")
if name in grade_book.keys():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
name = raw_input("Name: ")
# Write dictionary back to the file
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
out_line = name + ':' + scores + "\n"
File.write(out_line)
File.close()
Unfortunately you would have to go over the file, find the correct line, edit it and write in a temp file and then move that file to original. Best first use a data structure like dict etc. to update scores and finally when done write or persist them.
def filehandle(name,correct):
temp = open('temp', 'wb')
with open('Test.txt', 'r') as f:
for line in f:
if line.startswith(name):
line = line.strip() + correct +'\n'
temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')
You need to pass in the parameters while calling the functions.
Name = input("Name: ")
correct = input("Number: ")
filehandle(name, correct)

Categories