Python: printing strings from another file - python

I want to call a file, erase its data, write new lines and print it.
Below is my program and its output.
from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()
Output:
[]
[]

So, your error (by your comments is that it isn't letting you read).
This is because your trying to read using a file pointer which was used to open the file in write mode.
from sys import argv
string, filename = argv
with open(filename, 'w') as text:
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
with open(filename, 'r') as text:
...

So adding seek(0) will do the job here.
seek(0) set the pointer at the beginning.
Here's the working code:
from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
text.seek(0)
new = text.read()
text.seek(0)
old = text.readlines()
print "%s" %(new)
print old
text.seek(0)
print text.readlines()
text.close()
Output:
hey
I was doing just fine before I met you
I drink too much and that's an issue but I'm okay
['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]
['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]

Related

Simple word counter program in python

I have tried to create a really simple program that counts the words that you have written. When I run my code, I do not get any errors, the problem is that it always says: "the numbers of words are 0" when it is clearly not 0. I have tried to add this and see if it actually reads anything from the file: print(data) . It doesn't print anything ): so there must be a problem with the read part.
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Thx in advance
This is beacuse you haven't closed the file after writing to it. Use f.close() before using z.read()
Code:
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
f.close() # closing the file here after writing
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Output:
copy ur text down below
hello world
the numbers of words are 2
After writing to f with f.write, you should close f with f.close before calling z.read. See here.

Find a dot in a text file and add a newline to the file in Python?

I read from a file, if it finds a ".", it should add a newline "\n" to the text and write it back to the file. I tried this code but still have the problem.
inp = open('rawCorpus.txt', 'r')
out = open("testFile.text", "w")
for line in iter(inp):
l = line.split()
if l.endswith(".")
out.write("\n")
s = '\n'.join(l)
print(s)
out.write(str(s))
inp.close()
out.close()
Try This ( Normal way ):
with open("rawCorpus.txt", 'r') as read_file:
raw_data = read_file.readlines()
my_save_data = open("testFile.text", "a")
for lines in raw_data:
if "." in lines:
re_lines = lines.replace(".", ".\r\n")
my_save_data.write(re_lines)
else:
my_save_data.write(lines + "\n")
my_save_data.close()
if your text file is not big you can try this too :
with open("rawCorpus.txt", 'r') as read_file:
raw_data = read_file.read()
re_data = raw_data.replace(".", ".\n")
with open("testFile.text", "w") as save_data:
save_data.write(re_data)
UPDATE ( output new lines depends on your text viewer too! because in some text editors "\n" is a new line but in some others "\r\n" is a new line. ) :
input sample :
This is a book. i love it.
This is a apple. i love it.
This is a laptop. i love it.
This is a pen. i love it.
This is a mobile. i love it.
Code:
last_buffer = []
read_lines = [line.rstrip('\n') for line in open('input.txt')]
my_save_data = open("output.txt", "a")
for lines in read_lines:
re_make_lines = lines.split(".")
for items in re_make_lines:
if items.replace(" ", "") == "":
pass
else:
result = items.strip() + ".\r\n"
my_save_data.write(result)
my_save_data.close()
Ouput Will Be :
This is a book.
i love it.
This is a apple.
i love it.
This is a laptop.
i love it.
This is a pen.
i love it.
This is a mobile.
i love it.
You are overwriting the string s in every loop with s = '\n'.join(l).
Allocate s = '' as empty string before the for-loop and add the new lines during every loop, e.g. with s += '\n'.join(l) (short version of s = s + '\n'.join(l)
This should work:
inp = open('rawCorpus.txt', 'r')
out = open('testFile.text', 'w')
s = '' # empty string
for line in iter(inp):
l = line.split('.')
s += '\n'.join(l) # add new lines to s
print(s)
out.write(str(s))
inp.close()
out.close()
Here is my own solution, but still I want one more newline after ".", that this solution not did this
read_lines = [line.rstrip('\n') for line in open('rawCorpus.txt')]
words = []
my_save_data = open("my_saved_data.txt", "w")
for lines in read_lines:
words.append(lines)
for word in words:
w = word.rstrip().replace('.', '\n.')
w = w.split()
my_save_data.write(str("\n".join(w)))
print("\n".join(w))
my_save_data.close()

learning Python the hard way argv and file

I am learning python from past weeks
from sys import argv
script,filename = argv
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write something to your file"
line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()
I want to view the contents of the file ,but when i use print filename or print filen it show name and open file on variable filen
you can read data using filen.read() or filen.readline() or filen.readlines()
1) read
fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()
2) readline
fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()
3) readlines.
fo = open(filename,read)
fo.readline() #read all the lines of a file in a list
fo.close()
Below document will give you better idea.
https://docs.python.org/2/tutorial/inputoutput.html
If you want to print the content of the file you opened, just use: print filen.read().
At its simplest:
from sys import argv
script,filename = argv
with open(filename) as f:
print f.readlines()
which dumps the files contents
or:
from sys import argv
script,filename = argv
with open(filename) as f:
lines=f.readlines()
for line in lines:
print line
which prints the lines out 1 by 1

Error: Getting symbols in python output

#I wrote the following code for making a text editor.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()
After the promp to write something in the file, the script goes awry and produces strange symbols instead of the typed text. Please help
You need to close and re-open your file.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
t.close() ##########
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
f.close() ##########
f = open(name, 'r+') ##########
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()

Why is target.write ignoring my %r formatting?

I'm trying to write a program similar to this guy's Learn Python the Hard Way program, near the top of the page.
http://learnpythonthehardway.org/book/ex16.html
This is my version below. But it tells me off for using "%r" at the end, why does it do that? I thought that's what you're meant to do in parenthesis.
# -- coding: utf-8 --
from sys import argv
script, filename = argv
print "Would you like file %r to be overwritten?" % filename
print "Press RETURN if you do, and CTRL-C otherwise."
raw_input('> ')
print "Opening the file ..."
target = open(filename, 'w')
target.truncate()
print "Now type three lines to replace the contents of %r" % filename
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "The lines below have now overwritten the previous contests."
target.write("%r\n%r\n%r") % (line1, line2, line3)
target.close()
You need to place the % operator directly after the format string. Take the parenthesis here:
target.write("%r\n%r\n%r") % (line1, line2, line3)
# --^
And move it to the end of the line:
target.write("%r\n%r\n%r" % (line1, line2, line3))
# --^
Also, I would like to mention that performing string formatting operations with % is frowned upon these days. The modern approach is to use str.format:
target.write("{0!r}\n{1!r}\n{2!r}".format(line1, line2, line3))

Categories

Resources