Reading text from a text file in python - python

I am having trouble trying to figure out how to import text from a text file easily or at least a memorable method. I am trying to make a program that insults the user (for school), that brings in a word/s from one text file, adds another word/s from the second file and the final word/s from the third text file...
I am having trouble finding a way of coding to do this...I have the random number up and running to pick the text I just need to know how to access strings or text in a text file.

The easiest way is to use the with statement. It takes care of closing the file for you.
with open("file.txt") as f:
for line in f:
# do something with line
Or read the data into directly into a list:
with open("file.txt") as f:
lines = list(f)
# do something with lines

Related

How to import and print seperate txt file in spyder?

I am trying to import several text files into my Spyder file, which I want to add to a list later on.
why does
test1 = open("test1.txt")
result in test1 as "TextIOWrapper"? How would I bring the content over into the python file?
Thanks in advance
You need to read the lines into your list after opening it. For example, the code should be:
with open('test1.txt') as f:
test1= f.readlines()
The above code will read the contents of your text file into the list test1. However, if the data in your text file is separated over multiple lines, the escape char '\n' will be included in your list.
To avoid this, use the below refined code:
test1= [line.rstrip('\n') for line in open('test1.txt')]

Python-Reading a string from a file, performing operations, reading the next string and performing the same operations

Im fairly new to python, I want to read a string from a file input that text using adb shell input text then go to the next line read the next string and input the next string by using the same command and this goes on for 200 lines
I think this will solve your problem, note the use of the readlines method:
your_file = open('path to your file', 'r') #this will open your file
lines = your_file.readlines() #this is an array of lines
for line in lines: #loop over the lines
<block of operations>

Writing to the end of specific line in python

I have a text file that contains key value pairs separated by a tab like this:
KEY\tVALUE
I have opened this file in append mode(a+) so I can both read and write. Now it may happen that a particular key has more than 1 value. For that I want to be able to go to that particular key and write the next value beside original one separated by a some delimiter(or ,).
Here is what I wish to do:
import io
ft = io.open("test.txt",'a+')
ft.seek(0)
for line in ft:
if (line.split('\t')[0] == "querykey"):
ft.write(unicode("nextvalue"));#Write the another key value beside the original one
Now there are two problems with it:
I will iterate through the file to see on which line the key is present(Is there a faster way?)
I will write a string to the end of that line.
I would be grateful if I can get help with the second point.
The write function always writes at the end of file. How should I write to the end of a specific line? I have searched and have not got very clear answers as to how to do that
You can read whole of file content, do your edit and write edited content to file.
with open('test.txt') as f:
lines = f.readlines()
f= open('test.txt', 'w')#open file for write
for line in lines:
if line.split('\t')[0] == "querykey":
line = line + ',newkey'
f.write('\n'.join(lines))

How do I delete multiple lines in a text file with python?

I am practicing my python skills by writing a Phone book program. I am able to search and add entries but I am having a lot of trouble deleting entries.
I am trying to find a line that matches my search and delete it as well as the next 4 lines. I have a function to delete here:
def delete():
del_name = raw_input("What is the first name of the person you would like to delete? ")
with open("phonebook.txt", "r+") as f:
deletelines = f.readlines()
for i, line in enumerate(deletelines):
if del_name in line:
for l in deletelines[i+1:i+4]:
f.write(l)
This does not work.
How would I delete multiple entries from a text file like this?
Answering your direct question: you can use fileinput to easily alter a text file in-place:
import fileinput
file = fileinput.input('phonebook.txt', inplace=True)
for line in file:
if word_to_find in line:
for _ in range(4): # skip this line and next 4 lines
next(file, None)
else:
print line,
In order to avoid reading the entire file into memory, this handles some things in the background for you - it moves your original file to a tempfile, writes the new file, and then deletes the tempfile.
Probably better answer: it looks like you have rolled a homemade serialization solution. Consider using a built-in library like csv, json, shelve, or even sqlite3 to persist your data in an easier-to-work-with format.

Append a text line to a file and remove the first one if there are more than 4 lines in python

I have an IRC client that people are chatting on while I broadcast my desktop. I wanted to show this on my broadcast and found a handy shock-wave flash title plug-in that can read text files and display them on the screen.
My IRC client uses python scripts and can call a function every time someone write a message.
I can write these text lines to a text file as they come in but I want some way of coding in python when there are more than 'say 4' lines of text in the file it removes the top one when adding the next one.
I planned to do so by reading the text file when the append line function is called, reading the last 3 lines adding the new one then re-writing it to the original file.
Of course when the script first runs there should be less then 3 lines in the file so the python should account for that also and only read the last 2 or 1 or 0 depending...
I tried writing some code in a previous question but it didn't work so I won't include it here.
You shouldn't give up too easily, the accepted answer to your previous question nearly did it.
You only need to do the following:
Open the input file, using a deque to obtain the last few lines, and append your new line
(don't forget to use a new line separator \n)
Re-open the file as an output file and write your collection of lines.
from collections import deque
path = 'test.txt'
with open(path, 'r') as file:
lines = deque(file, 4)
lines.append("\nthis is an additional line.")
with open(path, 'w') as file:
file.writelines(lines)

Categories