Trying to print only one line of a text document in python - python

I am making a program that lets you edit, or read a text document in python, and I'm not finished yet, and I'm stuck on the reading part. I want it to print only one line, and I'm drawing a blank on how to do so. The read part is in "def read():"
def menu():
print("What would you like to do?")
print("\n(1) Write new text")
print("(2) Read line 3")
choice = float(input())
if choice == 1:
write()
elif choice == 2:
read()
def read():
with open('test.txt', 'r') as read:
print()
def write():
print("\nType the full name of the file you wish to write in.")
file1 = input().strip()
with open(file1, "a") as add:
print("What do you want to write?")
text = input()
add.write("\n"+ text)
menu()

def read():
with open('test.txt', 'r') as f:
for line in f:
print(line)
Edit:
def read():
with open('test.txt', 'r') as f:
lines = f.readlines()
print lines[1]

You can use the file as an iterable, and loop over it, or you can call .next() on it to advance one line at a time.
If you need to read 1 specific line, this means you can skip the lines before it using .next() calls:
def read():
with open('test.txt', 'r') as f:
for _ in range(2):
f.next() # skip lines
print(f.next()) # print the 3rd line

I figured mine out pretty late since i do not use the 'def' function, but this prints out the line that you want to print
import os.path
bars = open('bars.txt', 'r')
first_line = bars.readlines()
length = len(first_line)
bars.close()
print(first_line[2])

Related

How do i change this so when i run the functions it adds to my .txt file?

Im supposed to make a function for adding name and number to a.txt file, and one for reading the file. What am I doing wrong and how do I correct it? first post so I dont know if something is in the wrong format, sorry.
def add():
while True:
name = input("Name and number: ")
with open("Telefon.txt", "a") as f:
f.write(name)
f.close()
if name == "Enter":
break
def read():
f = open("Telefon.txt", "r")
print(f.read)
There are certain logical and optimizations mistake in your code you should not open file again and again and close it in loop, also use empty condition to terminate the loop e.g. press enter without entering any thing. For reading, I replaced your read method with redlines method
def add():
with open("Telefon.txt", "a") as f:
while True:
name = input("Name and number: ")
f.write(name + '\n')
if name == "":
break
def read():
f = open("Telefon.txt", "r")
print("".join(f.readlines()))
add()
read()
The output is following

Text Files, and New Lines

If I have this code to write a txt file I am just wondering why every time I type \n in the input it doesn't create a newline so like this.
This is the example txt file\n it doesn't create a new line\n how can I make it do it?
This is the code
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text)
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(["\n", text])
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
You can use replace:
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text.replace('\\n', '\n'))
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(text.replace('\\n', '\n'))
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
Here's a very simplified answer.
input = input("Would you like to Write a new document, or Edit an existing one? ")
if input == Write:
file = open(path, "w")
file.write(text)
file.write("\r\n")
file.close()
if input == Edit:
file = open(path, "a")
file.write(text)
file.write("\r\n")
file.close()
The reason why \n doesn't work with input is mentioned in How do you input escape sequences in Python?. The input function doesn't recognize any escape sequences, such as \n, because it interprets the text literally.
To interpret \n as a new line from text, have these imports and adjust the arguments for write() and writelines() allowing a user to input, This is the example txt file\n it doesn't create a new line\n how can I make it do it? to include new lines:
import ast # Add imports
import shlex
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(ast.literal_eval(shlex.quote(text))) # Evaluate escape sequences
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(["\n", ast.literal_eval(shlex.quote(text))]) # Evaluate escape sequences
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()

Python says: "expected an indented block"

I've been playing around with Python a bit recently and have come across this error when creating functions. I can't seem to fix it :(. CODE:
Python
#Python
choice = input('Append Or Write?')
if choice == "write":
def write():
pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
if choice == "append":
def append():
# Making a txt file
#Append
pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
You forgot to call your functions that you defined. pass may also be causing the statements in your function to get ignored, remove pass.
Reformatting your code:
#Python
def append():
# Making a txt file
#Append
# pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
def write():
# pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
choice = input('Append Or Write?')
if choice == "write":
write()
if choice == "append":
append()

How do I permanently change a list after user's input?

hiddenWords = ['hello', 'hi', 'surfing']
print("Would you like to enter a new list of words or end the game? L/E?")
decision = input()
if decision == 'L':
print('Enter a new list of words')
newString = input()
newList = newString.split()
hiddenWords.extend(newList)
j = random.randint(0, len(hiddenWords) - 1)
secretWord = hiddenWords[j]
exit(0)
How do I permanently add the input of the user to the hiddenWords list so that next time I open the application the words the user has entered has been extended onto the hiddenWords list?
Thanks.
This Code is part of a main body of code.
When you write
hiddenWords = ['hello', 'hi', 'surfing']
You are, each time the program runs, defining the variable hiddenWords as ['hello', 'hi', 'surfing'] .
So no matter what you extend after this, every time the code runs the line above, it will redefine to that value.
What you are looking for actually is to use a Database, such as SQLite, to store values so that you can retrieve them at any time.
Also, you can save data in a file and read this everytime, which is a simpler way.
When your program exits, all variables are lost, because variables only exit in memory. In order to save your modification accross program executions (everytime you run your script), you need to save the data onto the Disk, i.e: write it to a file. Pickle is indeed the simplest solution.
I like json. This would be a possible solution:
import json
words = []
try:
f = open("words.txt", "r")
words = json.loads(f.read())
f.close()
except:
pass
print("list:")
for word in words:
print(word)
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()
if add:
words.append(add)
try:
f = open("words.txt", "w")
f.write(json.dumps(words, indent=2))
f.close()
print("added " + add)
except:
print("failed to write file")
If you want to add multiple words at a time use this.
import json
words = []
try:
f = open("words.txt", "r")
words = json.loads(f.read())
f.close()
except:
pass
print("list:")
for word in words:
print(word)
save = False
while True:
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()
if add:
words.append(add)
print("added " + add)
save = True
else:
break
if save:
try:
f = open("words.txt", "w")
f.write(json.dumps(words, indent=2))
f.close()
except:
print("failed to write file")

Show updated text file in python

Below is my python code:
filename = 'ToDo.txt'
def preview():
temp = open(filename, 'r')
print temp.read()
print '\n'
temp.close
def new_task():
temp = open(filename, 'a')
while True:
new_entry = raw_input('Enter New Task: ')
if new_entry == 'exit' or new_entry == 'quit':
break
if new_entry == 'preview':
print '\n'
preview()
break
temp.write(new_entry + '\n')
temp.close
I think it should display modified file with new entry saved if input is "preview", but it doesn't. Any idea to do the same.
EDIT2: Seeing the other answers, I realise your question may be interpreted in many different ways. The first part of my answer might or might not be the right one, but the second one is interpretation-neutral!
This answer assumes you are trying to see "preview" as the last line in your file.
It won't work because your are loading and printing the file before you saved it. Try substituting the relevant bit of your code with this:
if new_entry == 'preview':
temp.write(new_entry + '\n')
temp.close()
print '\n'
preview()
break
EDIT: If you are doing a lot of reading/writing/printing/previewing with your file, you might be interested in looking at the StringIO module. From the docs:
This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).
The idea in this case would be that you do all your file handling in memory and before quitting the program you simply save the entire "memory file" to a "disk file". The reason to prefer this approach is that I/O operations on disk are expensive, so if you do this a lot you might bog your program down [I understand with a ToDo program this might not be the case, yet I though it was interesting to mention.
HTH!
You are not actually calling any of your functions:
filename = 'ToDo.txt'
def preview():
temp = open(filename, 'r')
print temp.read()
print '\n'
temp.close
def new_task():
temp = open(filename, 'a')
while True:
new_entry = raw_input('Enter New Task: ')
if new_entry == 'exit' or new_entry == 'quit':
break
if new_entry == 'preview':
print '\n'
preview()
break
temp.write(new_entry + '\n')
temp.close
new_task() //adding this line will call the new_task() function
In python to call a function you need to explicitly state it at the bottom of the py file
You should change your code to:
def new_task():
while True:
temp = open(filename, 'a')
new_entry = raw_input('Enter New Task: ')
if new_entry == 'exit' or new_entry == 'quit':
break
if new_entry == 'preview':
print '\n'
preview()
break
temp.write(new_entry + '\n')
temp.close()
Two changes here:
not temp.close, but temp.close()
temp = open(filename, 'a') moved inside the loop to be executed each time
The program has temp.close. This isn't the proper way to call close(); thus the temp.write doesn't get done immediately. You need temp.close().

Categories