Adding More Lines - python

I am trying to make a small text creator application using Python. The concept is just the same as ordinary text creator (e.g. notepad). But I got difficulties to allow users to type a lot of paragraphs. So far, I am just able to allow users to type 2 paragraphs. Is there anyone can help me? Here is my script:
print "Welcome to 'Python Flat Text Creator'."
print "Please enter the name of your file and its extension (.doc atau .txt)."
filename = raw_input("> ")
target = open(filename, 'w')
typeyourtext = raw_input("Type below: \n")
target.write(typeyourtext + "\n")
typeyourtext = raw_input("\n")
target.write(typeyourtext + "\n")
target.close()

An easy answer would be to simply put the typing and displaying of the text in a while(true) block and waiting for something (key press or set of characters) to break the cycle. But I'm not sure if you want to do it this simple.
Try to go around it with inserting the characters one by one as other text editors - take a look at Vim for example. The system which is used there is fairly simple and convenient.
Edit:
Getting keypress: How to accept keypress in command line python?
Do while true cycle: http://wiki.python.org/moin/WhileLoop
at the end of each cycle if the input char isn't chr(27), which is ESC key, then append to the text which you are creating and display it.. but this isn't good for files which are large in size..

You can use a while loop set to end when the user does not input anything at all.
target = open(filename, 'w')
previousKeypress = 0
print("Type below:\n")
while previousKeypress != "":
typeyourtext = raw_input("")
target.write(typeyourtext + "\n")
previousKeypress = typeyourtext
target.close()
If you intend for users to put additional new lines in the document through no inputs, you can set the condition to react to a certain combination of characters like maybe "abc123" to end it.
You can even ask the user to set this ending combination through another raw_input at the very beginning of the program.

Related

How to change specific part of a text file without deleting the rest?

I am trying to code a python program that stocks the username, password and score you've entered. That part I believe to be working. My issue is when I reopen the program, I want to have the new score from that username and password added onto the old score, but what I've tried either deletes the rest of the text file or modifies the password as well as the score (say it wrote <123> <2> and you wrote 2 as the score next time, it would become <143> <4>). I only want it to change the score but not the password or username, how do I go about this?
Here's some part of the code I having difficulties with:
In the following, here's what is written in the text file -- nate 123 2
for line in open("test.txt","r").readlines():
score_info = line.split()
if user == score_info[0] and password == score_info[1]:
oldscore = int(score_info[2])
newscore = int(count) + oldscore
score_info[2] = str(newscore)
file = open("test.txt","r+")
file.write(score_info[0])
file.write(" ")
file.write(score_info[1])
file.write(" ")
file.write(score_info[2])
file.write("\n")
file.close()
It sounds like there could be multiple solutions. Perhaps three text files?
Since it is work with strings in a singular text file, a nice tool to have in your back pocket is Regular Expressions. If you want to take the time to learn about them, they would be well suited to this task and many others you'd have in the future.
If you have time to paste the code; it would be helpful.

How do I run this check even at all times

I want to check if a file has a new line added to it but the check does not do what its supposed to do.
while True:
with open("text.txt", "r") as file:
currentLines = len(file.readlines())
if currentLines != totalLines:
totalLines = currentLines
get_latest_message()
print(totalLines)
else:
myMessage = input("type a message: ")
send_message(myMessage)
The program is supposed to use get_latest_message() if the text file is edited but this does not work because the check is only executed after you send a message because of the way the loop is structured, and because get_latest_message() only prints the latest message (yours since you just sent it) and skips over any sent in between.
Basically, I want to run the above code even while stopped at the myMessage = input("type a message: ") part. Thanks!
Trying putting each seperate component of the program in seperate threads using the threading library. You could loop through and check if any new text was added to the file in one thread, while the other thread could be checking whether the user input any text, and writing it to the file.

How to retrieve and write specific items from list to a file in Python

UPDATE
So I added strip() to list1. I am including the updated results.
updated output file
location?bobThings things thingyes, bob, thing, sara, more, location, ?
Yes, this is all returned on the one line.
It did miss the yes in the search, and now it is all one line smashed together.
How do I get it so that it returns with the spaces like before and on a new line for each positive result?
So, I'm new to python and still learning. I am writing a program that would allow a user to input keywords and search a input file for these keywords, then save the results to an output file.
So far, I can get it to do the search, but it is only returning certain lines from positive hits instead of all the lines. I originally thought this was because the of the new line attached to each item in the file, but I managed to strip that away and it is still not providing the correct information in the output file.
So the input file says:
Temp Chat Log
age
sex
location
?
sex
age
phone number
words
bob
Things things thing
09/03/2018
The keyword search is (user input):
yes, bob, thing, sara, more, location, ?
The output file is only getting this return:
Things things thing
I have tried removing the '\n', I have tried saving to a new file just in case there was something wrong with the original one I'm overwriting, I have tried re.search and re.replace, I've tried making a function but this is the closest I've gotten to getting the program to do this piece. The problem, I think, is with the last section of code, but I'm providing code for all pieces used in that last section. In the final section there are extra print lines because I was trying to see what was happening with the code as it progressed through this section of the program.
# Ask user for the path to the text file they would like to use
print ("Please provide a valid path to the chat log text (.txt) file. Example: C:\ Users \ USERNAME \ Documents")
# Save the path from the user input
path1 = input ()
# Checking the user input for the .txt file extension
if os.path.splitext(path1)[1] != ".txt":
print (path1 + " is an unknown file format. Please provide a .txt file.")
path1 = input()
else:
print ("Thank you for providing a text file.")
# Using a while loop to ensure this is a valid path
while not os.path.isfile(path1):
print ("Please provide a valid path to the chat log text (.txt) file.")
path1 = input ()
print ("File was successfully retrieved.")
# Ask user for needed keywords or symbols
user_keywords = input("What keywords or special symbols would you like to search the provided file for?\n"
"Please separate each entry with a comma.\nIf you would like to just search for question marks,"
" please just type n.\n")
# Holding list, using comma as a way to separate the given words and symbols
list1 = [s.strip().lower() for s in user_keywords.split(',')]
# Print list for user to see
print("You have entered the following keywords and/or special symbols: ", list1)
# Opens a new file for saving the results to.
print("Please list the path you would like the new file to save to. Example: C:\ Users \ NAME \Desktop\File name.")
outFileName = input()
# Opens the file under review.
with open(path1,'r') as f, open(outFileName, 'w') as w:
f = f.readlines()
f[:] = [f.rstrip('\n') for f in f]
for line in f:
if any(s in line.lower() for s in list1):
print(f)
print(list1)
print(line)
w.write(line)
w.close()
No error messages.
Expected Output See above update
New file at given output file path, with the positive result lines listed. So in this case, the file should have these lines on it.
bob
Things things thing
location
?
Current Output See above update
The only positive return that is happening is:
Things thing thing

Python 3.7 - how to index console commands to use as a reference

I'm learning Python and stuck with below task thus appreciate some help. (version 3.7)
Task: Record console inputs into a file - assign an ID to it to be able to delete based on the ID. Be able to list it.
Full code below for reference - yet I struggle with assigning an index to the user input and delete it based on that ID. I was advised that it is possible relying on sys.argv - yet I kinda feel this is rather expecting a dictionary usage (which I am not familiar with yet).
I was trying to add a number prior to the user input in the file (so the text file would look like 001. *user input*,\n 002. *user input*, etc), thus all lines shall get numbered.
Based on that when the user enters a certain number(=certain line) to be deleted the script should delete the given line. Yet I failed to look up and make python understand the number reference at the beginning of the line (some sort of search function would work I assume).
Can I tell the script to delete based online reference?
edit: given that the program shuts down after every entry len(sys.argv) will remain 1. A possible solution could be -if I don't shut it down- to refer to the index number to delete certain line based on the reference. But how do I feed again the variable/index number after restarting the program? The index will start again from 1 (as 0 reserved) and will disregard the number of lines already in the text.
Thanks in advance!
import sys
menu = input("What o you want to do?\n add new idea(1)\n delete an idea(2)\n list all ideas(3)")
if menu == "1":
myfile = open("ideabank.txt", 'a+', encoding = 'utf-8')
newidea = input("What is your new idea?:")
print('Argument List:', str(sys.argv))
myfile.write(newidea)
myfile.write("\n")
myfile.close()
elif menu == "2":
print("delete")
else:
myfile = open("ideabank.txt", 'r', encoding = 'utf-8')
for line in myfile:
print(line, end="")
myfile.close()
myfile = open("ideabank.txt", 'r+', encoding = 'utf-8')
newidea = input("Which line you want to delete:")
data = myfile.readlines()
for i in range(0, len(data))
if i != int(newidea):
myfile.write(data[i])
myfile.write("\n")
myfile.close()
Just to close the question for any future possible check.
The solution I used was to use list in lists. Thus the index of the element was the ordering and the tasks and the completion status was the 0 and 1 elements of the list-in-lists.

Checking data from a text file

I've been trying to create a program that takes an input and checks to see whether that input is in some text from a file. My end goal is to create a user login GUI, but I will not show the code for the GUI here as there is quite a lot.
I need to work out how to compare text from an input and from the file.
This is my code so far
def check(entry):
search = open('password.txt', 'r')
if str(entry) in str(search):
return (entry, "Word found")
else:
return entry, ("Word not found")
with open('password.txt', 'r') as text:
print (text.read())
while True:
entry=input("\nSearch for word: ")
print(check(entry))
When I run the code it will say that 1, 2, 5 and 12 are all in the text but none of the words that are in text are confirmed.
If anyone could help it would be appreciated, thanks.
Ignoring the security bad ideas covered in another comment, str(search) doesn't work like you think it does. If you print it, you should see something like:
<open file 'password.txt', mode 'r' at 0x0000000001EB2810>
which is a description of the object you created with the open function. You need to read the file into a string first with the .read() method.

Categories

Resources