How to read specific word of a text file in Python - python-2.x

Output.txt = report_fail_20150818_13_23.txt
I want to read output.txt from 8th character to 11th so that it can print fail.
fo = open("output.txt", "r+")
str = fo.read(8,11);
print "Read String is : ", str
fo.close()

You need to read the line first, then get the word from that line. Use the .readline() method (Docs).
Here is the correct way according to the example in the question:
fo = open("output.txt", "r+")
str = fo.readline()
str = str[7:11]
print "Read String is : ", str
fo.close()
However, for the best practise use a with statement:
with open('myfile.txt', 'r') as fo:
str = fo.readline()
str = str[7:11]
print "Read String is : ", str
with automatically closes the file when the block ends. If you are using Python 2.5 or lower, you have to include from __future__ import with_statement.

Related

Remove " " from line Ruby

I have a loop which read lines from text file :
text = File.open("file.txt").read
text.gsub!(/\n\r?/, "\n", )
text.each_line do |line|
# do something with line
end
And in each iteration I get line with " " in the end of line : "word ", and I need get just "word"
How fix my problem?
ll = line.clone.sub!(" ", "") - returns nil
You might want to use String#strip or one of the similar methods to remove whitespace. In this example String#rstrip seems to be an option:
text.each_line do |line|
sanitized_line = line.rstrip
# ...
end
line.gsub!(/\s+/, "") - fixed my problem.

Replace whole line with sub-string in a text file - Ruby

New to ruby here!
How to replace the whole line in a text file which contains a specific string using ruby?
Example: I want to remove and add the whole line contains "DB_URL" and add something like "DB_CON=jdbc:mysql:replication://master,slave1,slave2,slave3/test"
DB_URL=jdbc:oracle:thin:#localhost:TEST
DB_USERNAME=USER
DB_PASSWORD=PASSWORD
Here is your solution.
file_data = ""
word = 'Word you want to match in line'
replacement = 'line you want to set in replacement'
IO.foreach('pat/to/file.txt') do |line|
file_data += line.gsub(/^.*#{Regexp.quote(word)}.*$/, replacement)
end
puts file_data
File.open('pat/to/samefile.txt', 'w') do |line|
line.write file_data
end
Here is my attempt :
file.txt
First line
Second line
foo
bar
baz foo
Last line
test.rb
f = File.open("file.txt", "r")
a = f.map do |l|
(l.include? 'foo') ? "replacing string\n" : l # Please note the double quotes
end
p a.join('')
Output
$ ruby test.rb
"First line\nSecond line\nreplacing string\nbar\nreplacing string\nLast line"
I commented # Please note the double quotes because single quotes will escape the \n (that will become \\n). Also, you might want to think about the last line of your file since it will add \n at the end of the last line when there will not have one at the end of your original file. If you don't want that you could make something like :
f = File.open("file.txt", "r")
a = f.map do |l|
(l.include? 'foo') ? "replacing string\n" : l
end
a[-1] = a[-1][0..-2] if a[-1] == "replacing string\n"
p a.join('')

Replace a specific line in a file using Ruby

I have a text file (a.txt) that looks like the following.
open
close
open
open
close
open
I need to find a way to replace the 3rd line with "close". I did some search and most method involve searching for the line than replace it. Can't really do it here since I don't want to turn all the "open" to "close".
Essentially (for this case) I'm looking for a write version of IO.readlines("./a.txt") [2].
How about something like:
lines = File.readlines('file')
lines[2] = 'close' << $/
File.open('file', 'w') { |f| f.write(lines.join) }
str = <<-_
my
dog
has
fleas
_
FNameIn = 'in'
FNameOut = 'out'
First, let's write str to FNameIn:
File.write(FNameIn, str)
#=> 17
Here are a couple of ways to replace the third line of FNameIn with "had" when writing the contents of FNameIn to FNameOut.
#1 Read a line, write a line
If the file is large, you should read from the input file and write to the output file one line at a time, rather than keeping large strings or arrays of strings in memory.
fout = File.open(FNameOut, "w")
File.foreach(FNameIn).with_index { |s,i| fout.puts(i==2 ? "had" : s) }
fout.close
Let's check that FNameOut was written correctly:
puts File.read(FNameOut)
my
dog
had
fleas
Note that IO#puts writes a record separator if the string does not already end with a record separator.1. Also, if fout.close is omitted FNameOut is closed when fout goes out of scope.
#2 Use a regex
r = /
(?:[^\n]*\n) # Match a line in a non-capture group
{2} # Perform the above operation twice
\K # Discard all matches so far
[^\n]+ # Match next line up to the newline
/x # Free-spacing regex definition mode
File.write(FNameOut, File.read(FNameIn).sub(r,"had"))
puts File.read(FNameOut)
my
dog
had
fleas
1 File.superclass #=> IO, so IO's methods are inherited by File.

How to actually write a newline to a string

How can I make this
content[i].gsub("\n", "\\n")
write (something like) this to a file
str = "some text\n"
I'm writing a piece of code to take a file and build a single string out of it that can be inserted back into the source code your working with, if that helps at all
If I'm mistaken and my error is actually somewhere else in the code, here is:
#!/bin/usr/ruby
#reads a file and parses into a single string declaration in language of choice
#another little snippet to make my job easier when writing lots of code
#programmed by michael ward
# h3xc0ntr0l#gmail.com | gists.github.com/michaelfward
# ***************************************
# example scrips
# with writefiles
# | writefiles [file with paths] [file to write*]
# | makestring [file to write* (actually is read, but same as above)] [lang]
#****************************************
def readFile(path)
fd = File.open(path, "r")
content = []
fd.each_line {|x| content.push(x)}
content = fixnewlines(content)
str = content.join()
str
end
def fixnewlines(content)
content.each_index do |i|
content[i].gsub("\n", "\\n")
end
end
def usage
puts "makestring [file to read] [language output]"
exit
end
langs = {"rb"=>"str =", "js" => "var str =", "c"=> "char str[] ="}
usage unless ARGV.length == 2
lang = ARGV[1]
path = ARGV[0]
str = readFile(path)
if langs[lang] == nil
if lang == "c++" || lang == "cpp" || lang == "c#"
puts "#{lang[c]}#{str}"
else
puts "unrecognized language found. supported languages are"
langs.each_key {|k| puts " #{k}"}
exit
end
else
puts "#{langs[lang]} #{str}"
end
Just remove fixnewlines and change readFile:
def readFile(path)
File.read(path).gsub("\n", '\n')
end
Hope it helps. On Windows use \r\n instead of \n. There's no need to escape slashes inside single brackets.
It depends on which platform you're using. Unix uses \n as line ending characters, whereas windows uses \r\n. It looks like you're replacing all new line characters though with \\n which escapes the new line character which I would not expect to work on either platform.

Why doesn't puts() print in a single line?

This is a piece of code:
def add(a, b)
a + b;
end
print "Tell number 1 : "
number1 = gets.to_f
print "and number 2 : "
number2 = gets.to_f
puts "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
When I run it, my results are spread over several lines:
C:\Users\Filip>ruby ext1.rb
Tell number 1 : 2
and number 2 : 3
3.0+3.0 =
5.0
C:\Users\Filip>
Why doesn't puts() print in a single line, and how can keep the output on one line?
gets() includes the newline. Replace it with gets.strip. (Update: You updated your code, so if you're happy working with floats, this is no longer relevant.)
puts() adds a newline for each argument that doesn't already end in a newline. Your code is equivalent to:
print "#{number1}+#{number2} = ", "\n",
add(number1, number2) , "\n",
"\n"
You can replace puts with print:
print "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
or better:
puts "#{number1}+#{number2} = #{add(number1, number2)}"
Because puts prints a string followed by a newline. If you do not want newlines, use print instead.
Puts adds a newline to the end of the output. Print does not. Try print.
http://ruby-doc.org/core-2.0/IO.html#method-i-puts
You might also want to replace gets with gets.chomp.
puts "After entering something, you can see the the 'New Line': "
a = gets
print a
puts "After entering something, you can't see the the 'New Line': "
a = gets.chomp
print a

Resources