Using Python and Ruby To Read Files

Problem:  You have a Python program that reads in a file named coolFile (in /tmp), and outputs the content to the screen.  The program prints an extra blank line after each line of content of the file named coolFile.  You want the output to not have an extra blank line.  Here is the code:

#/usr/bin/python

x = open("/tmp/coolFile", "r")
for line in x:
        print (line)

How do you have the output now print an extra blank line after each line?

Solution:  Insert a comma after the print (line) stanza.  Here is an example of source code that works:

#/usr/bin/python

x = open("/tmp/coolFile", "r")
for line in x:
        print (line),

Equivalent program in Ruby:  Here is the equivalent method in Ruby (a program that reads in a file, /tmp/coolFile, and prints each line out with no extra line):

#/usr/bin/ruby

File.readlines('/tmp/coolFile').each do |line|
    puts line
end

Leave a comment

Your email address will not be published. Required fields are marked *