What did I wrong here [Write to file in new line]? - python

I want to make a simple function that writes two words to a file each on a new line.
But if I run this code it only writes "tist - tost" to the file.
Code:
def write_words(word1, word2):
w = open("output.txt", "w")
w.write(word1 + " - " + word2 + '\n')
w.close()
write_words("test", "tast")
write_words("tist", "tost")
Output:
tist - tost
How can I write the two phrases to the file?

You need to open your file in append mode, also as a more pythonic way for opening a file you can use with statement which close the file at the end of block :
def write_words(word1, word2):
with open("output.txt", "a") as f :
f.write(word1 + " - " + word2 + '\n')

Related

How to delete the last line of my output file?

Been trying to write my PYTHON code but it will always output the file with a blank line at the end. Is there a way to mod my code so it doesn't print out the last blank line.
def write_concordance(self, filename):
""" Write the concordance entries to the output file(filename)
See sample output files for format."""
try:
file_out = open(filename, "w")
except FileNotFoundError:
raise FileNotFoundError("File Not Found")
word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
word_lst.sort() #orders it
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = "" #string that will be written to file
for c in ln_num:
ln_str += " " + str(c) #loads line numbers as a string
file_out.write(i + ":" + ln_str + "\n")
file_out.close()
Output_file
Line 13 in this picture is what I need gone
Put in a check so that the new line is not added for the last element of the list:
def write_concordance(self, filename):
""" Write the concordance entries to the output file(filename)
See sample output files for format."""
try:
file_out = open(filename, "w")
except FileNotFoundError:
raise FileNotFoundError("File Not Found")
word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
word_lst.sort() #orders it
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = "" #string that will be written to file
for c in ln_num:
ln_str += " " + str(c) #loads line numbers as a string
file_out.write(i + ":" + ln_str)
if i != word_lst[-1]:
file_out.write("\n")
file_out.close()
The issue is here:
file_out.write(i + ":" + ln_str + "\n")
The \n adds a new line.
The way to fix this is to rewrite it slightly:
ln_strs = []
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = " ".join(ln_num) #string that will be written to file
ln_strs.append(f"{i} : {ln_str}")
file_out.write('\n'.join(ln_strs))
Just btw, you should actually not use file_out = open() and file_out.close() but with open() as file_out:, this way you always close the file and an exception won't leave the file hanging

not writing all lines of output in a new file in python

I am creating a file and I want to write all lines of write_line to my output.
With this could I have a new file but only with the last line of write_log not all the lines. I think I should have a for before written log and tell to write all, but i am so new with python and need help.
I am getting name / familtname / id by SOAP response. I want to print responses which are in lines, now i just see the last line not all the lines.
timestamp = str(datetime.datetime.now())[:19]
file = open(CreateFile, 'w')
write_line = str(name).strip() + ';' + familyname.strip() + ';' + str(id).strip() + ';' + timestamp
file.writelines(write_line + '\n')
def CreateFile():#******************creating output log file*****
today = str(datetime.date.today()).split('-')
NowTime = str(datetime.datetime.now())[11:19:]
Nowtime_split = NowTime.split(':')
timestamp=Nowtime_split[0]+Nowtime_split[1]+Nowtime_split[2]
daystamp=today[0]+today[1]+today[2]
filename = 'log' + '_' + daystamp + '_' + timestamp + '.csv'
destfile = r'C:\Desktop' + str(filename)
file = open(destfile, 'w')
file.close()
return(destfile)
CreateFile=CreateFile()
this is a small case:
import datetime
timestamp = str(datetime.datetime.now())[:19]
file = open('1.txt', 'w')
for i in range(10):
write_line ='try'+str(i)
file.writelines(write_line + '\n')
file.close()
`
I'm not really sure what you want but I think the problem is because you're using write parameter to open the file and it's always replacing the previous text, so what you can do is replacing write with append(a):
timestamp = str(datetime.datetime.now())[:19]
with open(CreateFile, 'a') as file:
write_line = str(name).strip() + ';' + familyname.strip() + ';' +str(id).strip() + ';' + timestamp
file.write(write_line + '\n')
I suggest you to use with open... in order to avoid closing the file opened and other futures errors
lines = ['line1', 'line2', ...] # set of lines (list) you want to add in the current timestamp file
with open('current_timestampfile.txt', 'w') as f:
f.writelines("%s\n" % l for l in lines)

Opening and editing multiple files in a folder with python

I am trying to modify my .fasta files from this:
>YP_009208724.1 hypothetical protein ADP65_00072 [Achromobacter phage phiAxp-3]
MSNVLLKQ...
>YP_009220341.1 terminase large subunit [Achromobacter phage phiAxp-1]
MRTPSKSE...
>YP_009226430.1 DNA packaging protein [Achromobacter phage phiAxp-2]
MMNSDAVI...
to this:
>Achromobacter phage phiAxp-3
MSNVLLKQ...
>Achromobacter phage phiAxp-1
MRTPSKSE...
>Achromobacter phage phiAxp-2
MMNSDAVI...
Now, I've already have a script that can do it to a single file:
with open('Achromobacter.fasta', 'r') as fasta_file:
out_file = open('./fastas3/Achromobacter.fasta', 'w')
for line in fasta_file:
line = line.rstrip()
if '[' in line:
line = line.split('[')[-1]
out_file.write('>' + line[:-1] + "\n")
else:
out_file.write(str(line) + "\n")
but I can't get to automate the process for all 120 files in my folder.
I tried using glob.glob, but I can't seem to make it work:
import glob
for fasta_file in glob.glob('*.fasta'):
outfile = open('./fastas3/'+fasta_file, 'w')
with open(fasta_file, 'r'):
for line in fasta_file:
line = line.rstrip()
if '[' in line:
line2 = line.split('[')[-1]
outfile.write('>' + line2[:-1] + "\n")
else:
outfile.write(str(line) + "\n")
it gives me this output:
A
c
i
n
e
t
o
b
a
c
t
e
r
.
f
a
s
t
a
I managed to get a list of all files in the folder, but can't open certain files using the object on the list.
import os
file_list = []
for file in os.listdir("./fastas2/"):
if file.endswith(".fasta"):
file_list.append(file)
Considering you are able to change the contents of file name now you need to automate the process. We changed the function for one file by removing file handler which was used twice for the opening of file.
def file_changer(filename):
data_to_put = ''
with open(filename, 'r+') as fasta_file:
for line in fasta_file.readlines():
line = line.rstrip()
if '[' in line:
line = line.split('[')[-1]
data_to_put += '>' + str(line[:-1]) + "\n"
else:
data_to_put += str(line) + "\n"
fasta_file.write(data_to_put)
fasta_file.close()
Now we need to iterate over all your files. So lets use glob module for it
import glob
for file in glob.glob('*.fasta'):
file_changer(file)
You are iterating the file name, which gives you all the characters in the name instead of the lines of the file. Here is a corrected version of the code:
import glob
for fasta_file_name in glob.glob('*.fasta'):
with open(fasta_file_name, 'r') as fasta_file, \
open('./fastas3/' + fasta_file_name, 'w') as outfile:
for line in fasta_file:
line = line.rstrip()
if '[' in line:
line2 = line.split('[')[-1]
outfile.write('>' + line2[:-1] + "\n")
else:
outfile.write(str(line) + "\n")
As an alternative to the Python script, you can simply use sed from the command line:
sed -i 's/^>.*\[\(.*\)\].*$/>\1/' *.fasta
This will modify all files in place, so consider copying them first.

How do I print out to a .txt

For my code below i was wanting to print out a full sentences in which certain words from my word lists appear, aswell it would print out the word count underneath each specific word into a .txt file. I succesfully achieved this in the terminal but am really struggling to get it into a .txt. At the moment i can only seem to get it to print out the word count in the .txt but the sentences are still printing to terminal, does anybody know where i maybe going wrong? Sorry for my lack of knowledge beginner learning python. Thanks
import re, os
pathWordLists = "E:\\Python\WordLists"
searchfilesLists = os.listdir(pathWordLists)
pathWordbooks = "E:\\Python\Books"
searchfilesbooks = os.listdir(pathWordBooks)
lush = open("WorkWork.txt", "w")
def searchDocs(word):
for document in searchfilesbooks:
file = os.path.join(pathWordbooks, document)
text = open(file, "r")
hit_count = 0
for line in text:
if re.findall(word, line):
hit_count = hit_count +1
print(document + " |" + line, end="")
print(document + " => " + word + "=> "+ str(hit_count), file=lush)
text.close()
lush.flush()
return
def searchWord():
for document in searchfilesLists:
file = os.path.join(pathWordLists, document)
text = open(file, "r")
for line in text:
#print(line)
searchDocs(line.strip())
text.close()
print("Finish")
searchWord()
In case you're printing sentences with print(document + " |" + line, end="") you forgot the file parameter. Adding it should fix the problem:
print(document + " |" + line, end="", file=lush)
Try storing the result in a variable and then writing the variable to the file. Something like this:
def searchDocs(word):
results = []
for document in searchfilesbooks:
file = os.path.join(pathWordbooks, document)
with open(file, "r") as text:
lines = text.readlines()
hit_count = 0
for line in lines:
if re.findall(word, line):
hit_count += 1
results.append(document + " |" + line)
results.append(document + " => " + word + "=> "+ str(hit_count))
with open("WorkWork.txt", "w") as f:
f.write('\n'.join(results))

Python search for text over multiple lines

import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
for line in currentFile:
if searchquery in line:
start = line.find(searchquery)
end = line.find("R")
result = line[start:end]
print result
f.write(result + ' ' +filename[:-4] + '\n')
Now this works well to search for "word" and prints everything after word up until an "R" providing that it is on the same line. However if the "R" is on the line it won't print the stuff before it.
eg:
this should not be printed!
this should also not be printed! "word" = 12345
6789 "R" After this R should not be printed either!
In the case above the 6789 on line 3 will not be printed with my current. However i want it to be. How do i make python keep going over multiple lines until it reaches the "R".
Thanks for any help!
It is normal that it does not print the content on the next line because you are searching for the word on one line. A better solution would be as follows.
import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
content = ''.join([line for line in currentFile])
start = content.find(searchquery)
end = content.find("R")
result = content[start:end].replace("\n", "")
print result
f.write(result + ' ' +filename[:-4] + '\n')
Please be advised, this will work only for a single occurence. You will need to break it up further to print multiple occurences.

Categories

Resources