Making a reversed file without complications - file

I was attempting to take a file, reverse it, and save it to another file. However, I've come across a problem.
If I reverse this, for example:
The woods are lovely, dark and deep.
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
I should end up with this:
And miles to go before I sleep.
And miles to go before I sleep,
But I have promises to keep,
The woods are lovely, dark and deep.
However, what I end up getting is this:
And miles to go before I sleep.And miles to go before I sleep,
But I have promises to keep,
The woods are lovely, dark and deep.
This is my code, at the moment:
import os.path
endofprogram = False
try:
fileName = input("Enter the name of the input file: ")
print("\n")
infile = open(fileName, 'r')
outfileName = input("Enter the name of the output file: ")
print("\n")
while os.path.isfile(outfileName):
outfileName = input("File Exists. Enter name again: ")
print("\n")
outfile = open(outfileName, 'w')
except IOError:
print("Error opening file - End of program")
endofprogram = True
if endofprogram == False:
lines = infile.readlines()
for reverse in lines[::-1]:
print(reverse)
outfile.write(reverse)
outfile.close()
infile.close()
Why is this happening and how can I fix it? Thank you.

It looks like the last line of your input file doesn't end in a newline. There's a number of ways to deal with that; here's one:
for reverse in lines[::-1]:
if reverse[-1] != "\n":
reverse += "\n"
#etc

Related

Execute if else condition parallelly over list of strings

I'm new in python and facing an issue in getting the right output. I have a list of strings as :
list_string=[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
All I want output as:
Output expected: [['The course starts next Sunday'], ["I don't wash the dishes"], 'When does the train usually leave']
What I've done is something:
import re
subtring='!DOC'
output=[]
for i in string:
if subtring in i:
text=re.findall("<p>(.*?)</t>",i, re.DOTALL)
output.append(text)
elif subtring in i:
text=re.findall("<d>(.*?)</span>",i, re.DOTALL)
output.append(text)
else:
output.append(i)
print (output)
[['The course starts next Sunday'], ["class='default'<d>I don't wash the dishes</span>"], 'When does the train usually leave']
Can anyone suggest the right way to do it?
It appears as though the second rule trumps the first so if there is a match on the second rule, use it otherwise try the first rule falling back to returning what you were given.
A solution that is close to what you have now might be:
import re
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output=[]
for line in list_string:
retval = re.findall("<d>(.*?)</span>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
retval = re.findall("<p>(.*?)</t>", line, re.DOTALL)
if retval:
output.append(retval[0])
continue
output.append(line)
print (output)
Though if it was me, I would probably use a little function with a comprehension:
import re
def pick_out_text(text):
retval = re.findall("<d>(.*?)</span>", text, re.DOTALL)
if retval: return retval[0]
retval = re.findall("<p>(.*?)</t>", text, re.DOTALL)
if retval: return retval[0]
return text
list_string =[
'!DOC <p>The course starts next Sunday</t><div>',
"!DOC <p>class='default'<d>I don't wash the dishes</span></t>",
'When does the train usually leave'
]
output = [pick_out_text(line) for line in list_string]
print(output)

How do I get matches from a text file and output them in an array?

I'm using a text file with lines of movies. If a user inputs Oz, I want to output all the movies in the file that have the word Oz in it.
This is what I have so far.
puts "Enter the keyword you want to search for: "
keyword = gets
movies_file = File.new("movies.txt", "r")
movies = movies_file.read
movies_list = movies.split(" ")
match_list = []
movies_list.each do |w|
matchObj = w.match(keyword)
if matchObj then
matchlist.push(matchObj.captures[0])
end
end
match_list.each do |title|
puts title
end
Presuming you've got the file organized like this:
Wizard of Oz
Battlefield Earth
Twilight
Ozymandias
Then you can read it in this way:
lines = File.readlines('movies.txt').map(&:chomp)
Then to find matching lines:
matches = lines.grep(phrase)
There's no need for all the each stuff. Also the then on an if is almost never put in there, it's just useless decoration.

storing data into a file rather than returning to the terminal

i have this function: write_reversed_file(input_filename, output_filename) that writes to the given output file the contents of the given input file with the lines in reversed order. i just need the output to be written to the file (output_filename) rather than to the terminal (python shell).
the only part im missing is to store the output into the file.
i successfully managed to complete the reversing lines part.
def write_reversed_file(input_filename, output_filename):
for line in reversed(list(open(filename))):
print(line.rstrip())
def write_reversed_file(input_filename, output_filename):
s = ""
f = open(input_filename,"r")
lines = f.read().split("\n")
f.close()
for line in reversed(lines):
s+=line.rstrip()+"\n"
f = open(outPutFile.txt,"w")
f.write(s)
f.close()
It is good practice to use 'with open as' format when working with files since it is automatically closing the file for us. (as recommended in docs.python.org)
def write_reversed_file(input_filename, output_filename):
with open(output_filename, 'w') as f:
with open(input_filename, 'r') as r:
for line in reversed(list(r.read())):
f.write(line)
write_reversed_file("inputfile.txt", "outputfile.txt")

Python Simple PiggyBank Program

This is my Python Program that I have been having some issues with:
-- coding: cp1252 --
from time import gmtime, strftime
print("Welcome to the PiggyBank version 1.")
num_write = int(input("How much money would you like to store in your PiggyBank?"))
f = open("PiggyBanks_Records.txt", "w")
current_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
convert_1 = str(current_time)
convert_2 = str(int(num_write))
add_1 = ("\n" + convert_1 + " £" + convert_2)
add_2 = ("\n" + add_1) #Tried to make it so new line is added every time the program is run
final_record = str(add_2)
print("Final file written to the PiggyBank: " + final_record)
#Write to File
f.write(final_record)
f.close()
Right now whenever the program writes to the file it over-writes. I would preferably would like to keep, like a history of the amounts added. If anyone can help so the string that needs to be written to the .txt file goes down by one line and essentially keeps going for ever. I am also open to any suggestion on how I can shorten this code.
You need to open your file with append mode :
f = open("PiggyBanks_Records.txt", "a")
Using the 'w' write option with open automatically looks for the specified file, and deletes its contents if it already exists (which you can read about here) or creates it if it doesn't. Use 'a' instead to add / append to the file.

How do I check for pangrams in a line in ruby?

Some of you may notice I'm already back with the same painful code already. I'm not sure if the other question is still open or not once I accept an answer.
Now the problem is a little simpler. I found some code that checked for pangrams. It use to be def pangram?('sentence') but I needed line to go in there so I tried changing it to def pangram?(line). It doesn't seem to mesh well with my coding style and doesn't work. I tried to use .contain('a' . . 'z') to check for a pangram but someone I know tried that and it didn't work. Also google isn't much help either.
Any ideas for how I could check for pangrams in an if stmt?
# To change this template, choose Tools | Templates
# and open the template in the editor
# This program reads a file line by line,
#separating lines by writing into certain text files.
#PPQ - Pangrams, Palindromes, and Quotes
class PPQ
def pangram?(line)
unused_letters = ('a'..'z').to_a - line.downcase.chars.to_a
unused_letters.empty?
end
def categorize
file_pangram = File.new('pangram.txt', 'w')
file_palindrome = File.new('palindrome.txt', 'w')
file_quotes = File.new('quotes.txt','w')
File.open('ruby1.txt','r') do |file|
while line = file.gets
if(line.reverse == line)
file_palindrome.write line
elsif(pangram?(line)== true)
file_pangram.write line
else
file_quotes.write line
end
end
end
file.close
file_pangram.close
file_palindrome.close
file_quotes.close
end
end
my_ruby_assignment = PPQ.new
my_ruby_assignment.categorize
I'm partial to simpler syntax, something like
def pangram?(line)
('a'..'z').all? { |word| line.downcase.include? (word) }
end
if pangram?(line) then file_pangram.write line end
def pangram?(string)
str = string.chars.map(&:downcase)
letters =('a'..'z').to_a
result = true
letters.each do |l|
if !(str.include? l.downcase)
result = false
break
end
end
result
end

Resources