Trying to append quotes to each item in list. - python

I am trying to create a script that will take each line in my text file which includes one rule name in each of them. The first script I created worked (finished) but would delete everything in the file. I have been googling for past hour or so trying to take examples and apply them on my own but keep failing. The current script is as follows.
with open('TDAppendlist.txt', 'w') as file:
for line in file:
s = ('""')
seq = (file)
s.join(seq)
with open('TDAppendlist.txt') as file:
line = file.readlines()
for line in file:
line.join('"' + line + '"')
Neither of them are working. Could someone please point me in the correct direction? Thank you all for reading.

First, we'll read all the lines of the file into a list, then we can change them, and finally write them back to the file.
with open('TDAppendlist.txt') as file:
lines = list(file)
with open('TDAppendlist.txt', 'w') as file:
file.write('\n'.join(['"{}"'.format(line.rstrip('\n')) for line in lines]))
That last line can be written out to be more clear
lines = (line.rstrip('\n') for line in lines)
lines = ('"{}"'.format(line) for line in lines)
lines = '\n'.join(lines)
file.write(lines)

This produces an output file TDAppendlist_out that is just like the input, but with quotes surrounding the lines:
with open('TDAppendlist.txt', 'r') as f:
with open('TDAppendlist_out.txt', 'w') as f_out:
for line in f:
f_out.write('\"{}\"'.format(line))
This keeps the input file intact as is should you need it later, and avoids putting everything in the input file into memory all at once.

Related

Copying the first line in the .txt file and writing it to the last line Python

I have a txt file with 5 lines. I want to delete the first line copied after typing the text in the first line on the last line.
Example:
1
2
3
4
5
After:
2
3
4
5
1
my attempt
with open("equasisemail.txt", 'r') as file:
data = file.read().splitlines(True)
with open ("equasisemail.txt",'w') as fi:
fi.writelines(data[1:])
i use this to delete the first line.
read the lines using readlines (don't splitlines else you lose line terminator). Then write back the file using writelines then write the final line with a simple write
with open("equasisemail.txt", 'r') as file:
data = file.readlines()
# make sure the last line ends with newline (may not be the case)
if not data[-1].endswith("\n"):
data[-1] += "\n"
with open ("equasisemail.txt",'w') as fi:
fi.writelines(data[1:])
fi.write(data[0])
careful as if something bad happens during the write the file is destroyed. Better use another name, then rename once writing has completed. In which case what can be done is reading & writing at almost the same time on 2 separate filenames:
with open("equasisemail.txt", 'r') as fr,open ("equasisemail2.txt",'w') as fw:
first_line = next(fr) # manual iterate to get first line
for line in fr:
fw.write(line)
if not line.endswith("\n"):
fw.write("\n")
fw.write(first_line)
os.remove("equasisemail.txt")
os.rename("equasisemail2.txt","equasisemail.txt")
safer & saves memory. Fails if the file is empty. Test it first.
note: both solutions support files that don't end with a newline character.
To edit a file without creating a new file you can save the contents of the file to main memory, then open it in write mode:
input = open("email.txt", "r")
lines = input.readlines()
input.close()
output = open("email.txt", "w")
for i in range(1, len(lines)):
output.write(lines[i].strip() + "\n")
output.write(lines[0])

Concenating to every value in a list

So I have a file with some lines of text:
here's a sentence
look! another one
here's a third one too
and another one
one more
and I have some code that takes the each line and puts it into a list and then reverses the order of the whole list but now I don't know how to write each line back to the file and delete the existing ones in the text file.
Also when I run this code:
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
everything works and the line order is reversed, but when I run this code:
text_file = open(file_name, "w")
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
for line in file_lines:
text_file.write(line)
it prints empty lists for some reason.
You can fix it by doing just 2 little changes in your script.
Use \r+ in place of \w+
Before performing write operation, place file position indicator to the beginning
text_file.seek(0)
» rw_file.txt - before operation
here's a sentence
look! another one
here's a third one too
and another one
one more
Below is your modified script to reverse the content of file (It worked).
def reverseFile(file_name):
text_file = open(file_name, "r+") # Do not use 'w+', it will erase your file content
file_lines = [line.rstrip('\n') for line in text_file.readlines()]
file_lines.reverse()
print(file_lines)
text_file.seek(0) # Place file position indicator at beginning
for line_item in file_lines:
text_file.write(line_item+"\n")
reverseFile("rw_file.txt")
» rw_file.txt - after operation
one more
and another one
here's a third one too
look! another one
here's a sentence
If you open the file in 'w' mode, the file is erased. From the docs:
'w' for only writing (an existing file with the same name will be
erased)
You should also use the with keyword:
It is good practice to use the with keyword when dealing with file
objects. The advantage is that the file is properly closed after its
suite finishes...
I would recommend you read the contents of the file first, process that data, and then write:
def reverseFile(file_name):
with open(file_name, 'r') as f:
file_lines = [line.rstrip('\n') for line in f.readlines()]
file_lines.reverse()
with open(file_name, "w") as f:
for line in file_lines:
f.write(line + '\n')
reverseFile('text_lines.txt')

From excel to txt - Separate lines

I'm doing a program where I export an excel file to .txt and I have to import this .txt file into my program. The main goal is to extract the same part from each line but the problem is that in the .txt file the lines of the excel are being made into a huge string with no /n. Do you know if there is a way to separate them within the program and if so how can I do it?
The file I'm working with can be downloaded in http://we.tl/YtixI1ck6l
and so far I was trying something like
ppi = []
for line in read_text:
prot_interaction = line[0:14]
ppi.append(prot_interaction)
result_ppi = []
for line in read_text:
result = line[-1]
result_ppi.append(result)
But since it's not formatted in lines but just in a single one I'm not getting any good results.
Using that file as an example, use the csv module to parse it.
Example:
import csv
with open('/tmp/Model_Oralome.txt', 'rU') as f:
reader=csv.reader(f, delimiter="\t")
for row in reader:
print row[0]
Prints:
ppi
C4FQL5;Q08426
C8PB60;D2NP19
P40189;Q05655
P22712;Q9NR31
...
P05783;P02751
B5E709;D2NPK7
Q8N7J2;Q9UKZ4
(BTW, the issue you may be having with this particular file is the line terminations are a CR only from a Mac Classic OS. You can fix that in Python by using the Universal Newline mode when you open the file...)
Excel is exporting the text file with carriage returns (\r) instead of newlines (\n).
ppi = []
with open("Model_Oralome.txt",'r') as f:
lines = f.readlines()
lines = lines[0].split('\r')
From here you can iterate through each line of lines. Since it looks like you want the value of the first column:
lines = lines[1:]
for line in lines:
content = line.split('\t')
ppi.append(content[0])

file open() , readLines()

import os.path
os.path.exists('~/fileToExperiment.txt')
myfile = open('~/fileToExperiment.txt','r')
myfile.readlines()
for line in myfile:
print line
So I am trying to run this very simple python code but it doesnot output anything nor does it has any errors.
The filestoExperiment text is not empty.
Whats wrong here ? Could someone point out
By doing, myfile.readlines() you already read the entire file. Then, we you try to iterate over your file object, you already are at the end of the file.
A better practice is to do:
with open('~/fileToExperiment.txt','r') as myfile:
for line in myfile:
print line
myfile.readlines() will store the whole content of the file in memory. If you do not need the entire content at once, it is best to read line by line.
If you do need the entire content, you can use
with open('~/fileToExperiment.txt','r') as myfile:
content = myfile.read() ## or content = myfile.readlines()
Also note the use of the with statement, which is recommended when handling files (no need to close the file afterwards).
You didn't store the lines in a variable. So try this:
lines = myfile.readlines()
for line in lines:
print line
You can use either readlines() or looping file object to print or read the lines from file.
readlines() - returns the complete file as a "list of strings each separated by \n"
for example,
code:
print myfile.readlines()
output:
['Hello World\n', 'Welcome to Python\n', 'End of line\n']
Looping file object - You can loop over the file object for reading lines from a file. This is memory efficient, fast, and leads to simple code. For example,
code:
myfile = open('newfile.txt', 'r')
for line in myfile:
print line
output:
Hello World
Welcome to Python
End of line

read a file line by line and append word

I am a newbie to python and trying to read file line by line and append a word at the end of each line. The "print line" shows that the required word has got appended but the same thing not written back to the file as required . Appreciate your help.
#!/usr/bin/python
f=open('test1', 'r+')
for line in f:
line=line.strip("\n")
line=line +" " + 'test2'
print line
f.write(line)
f.close()
Generally speaking, reading/writing a file at the same time is a really horribly difficult thing to get right. Usually, you'll read from one file and write to a different file (possibly in memory). An in-memory implementation would be something like:
with open('test1', 'r') as fin:
lines = [line.strip('\n') + ' test2\n' for line in fin]
with open('test1', 'w') as fout:
fout.writelines(lines)
Notice that I read all the file's data into memory in the first with block. In the second with block, I write all that data back out to a new file (which conveniently has the same name as the old file effectively overwriting the old). Of course, if memory is a problem, you can read a line and then write a line to a new file (with a different name). After you've closed and flushed both files, then you can use shutil.move to rename the new file so that you overwrite the old one.
#mgilson's answer is very well, and just a little error is the lines in the end of lines = [line.strip('\n') + ' test2\n' for line in lines] should be fin.
The code given by mgilson is great! However, the function you request is not possible if you read and append at the same time.
I am too new to python.
So, I find myself more comfort in the following syntax.
# read in
f = open('test1', 'r')
newlines = []
for line in f:
newline = line.strip("\n") + " " + 'test2' + "\n"
newlines.append(newline)
print newline,
f.close()
# overwrite the same file
f = open('test1', 'w')
f.writelines(newlines)
f.close()
mgilson's code is slightly wrong. Corrected:
with open("test1", "r") as f:
new_contents = [line.strip() + "test2" for line in f.readlines()]
with open("test1", "w") as f:
f.write("\n".join(new_contents))

Categories

Resources