How to write the result in text file? - python

I tried to write the results in the text file. When I am printing the results I can be able to result but when I am moving the result I cannot see in the text file.
Here is the code that I have written
with open ('file.txt', 'r') as fp:
line = fp.readline(1)
while line:
line = fp.readline()
a=len(line)
b=line.find('The',0,a)
c=line.find('are',0,a)
b= b+4
b1=str(line[b:b+7])
c=c+4
c1=str(line[c:c+7])
var = ' '
var = "".join([b1, c1])
var1=str(var)
print (var)
with open ('new.txt', 'w') as file:
file.write(var)
result that I am seeing when printing but in the text file. Appending the text is working but I do not want to append the text every time I execute. I just want only once even if I execute n times.
eating mango
Help me where I am going wrong. Any help would be appreciated. Thank you

You need to call file.write, not just assign it to a variable:
with open ('new.txt', 'w') as file:
file.write (var)
Could this be what you need:
v = ''
with open ('file.txt', 'r') as fp:
line = fp.readline(1)
while line:
line = fp.readline()
a=len(line)
b=line.find('The',0,a)
c=line.find('are',0,a)
b= b+4
b1=str(line[b:b+7])
c=c+4
c1=str(line[c:c+7])
var = ' '
var = "".join([b1, c1])
var1=str(var)
v+=var+'\n'
with open ('new.txt', 'w') as file:
file.write(v)

think this might be this issue
file = file.write (var)
you're assigning it to a variable instead of just calling it, should be:
file.write(var)
also in the future if you plan on outputting several lines of code to a file, look into using the logging module ;) https://docs.python.org/3/library/logging.html

I've come up with two issues with your code.
1) Assigning file to the new file
Don't use the code file = file.write(var). Instead what you would want is: file.write(var)
2) File is already a built in
You shouldn't use this variable name, as it is already built in to python. Name the variable f or something else.
Here's a working example on repl.it Writing To A File.
Please comment if there are any other problems or questions.

Related

Write a multi line string to a text file using Python

I'm trying to write multiple lines of a string to a text file in Python3, but it only writes the single line.
e.g
Let's say printing my string returns this in the console;
>> print(mylongstring)
https://www.link1.com
https://www.link2.com
https://www.link3.com
https://www.link4.com
https://www.link5.com
https://www.link6.com
And i go to write that into a text file
f = open("temporary.txt","w+")
f.write(mylongstring)
All that reads in my text file is the first link (link1.com)
Any help? I can elaborate more if you want, it's my first post here after all.
never open a file without closing it again at the end.
if you don't want that opening and closing hustle use context manager with this will handle the opening and closing of the file.
x = """https://www.link1.com
https://www.link2.com
https://www.link3.com
https://www.link4.com
https://www.link5.com
https://www.link6.com"""
with open("text.txt","w+") as f:
f.writelines(x)
Try closing the file:
f = open("temporary.txt","w+")
f.write(mylongstring)
f.close()
If that doesn't work try using:
f = open("temporary.txt","w+")
f.writelines(mylongstring)
f.close()
If that still doesn't work use:
f = open("temporary.txt","w+")
f.writelines([i + '\n' for i in mylongstring])
f.close()

How do I create and write a file with for loop?

So I have a text file that has writing in it and I created a for loop which finds a specified string in the file and prints out the lines that have the string contained in it. But now I'm stuck because I want to modify the code so I can write a new file that contains what it already printed out.
I've tried researching around for answers, but I can't seem to find any solutions or how to even search for what I am trying to do. I tried carefully looking at the parameters of print function and join method.
file = open("datalist.txt", "r")
s = "hello"
file_export = open("newfile.txt", "w")
for lines in file:
lines = lines.lower()
index = lines.find(s)
if index != -1:
indexed = lines[index:]
print(lines[index:], end='')
The printed message I need is something along the lines of:
hello,
hello:
hello;
print is not the function you are looking for, to write into a file you need to use file.write (or file.writeline), take a look to the input and output documentation.
To give an idea, your code should be something like this:
file = open("datalist.txt", "r")
s = "hello"
file_export = open("newfile.txt", "w")
for lines in file:
lines = lines.lower()
index = lines.find(s)
if index != -1:
indexed = lines[index:]
print(lines[index:], end='')
file_export.write(lines[index:])
Also, note that you should close your file when you are done, so add the following at the end:
file.close()
file_export.close()
Or, as an alternative, use the context manager that automatically closes your file.

How to overwrite a file correctly?

I would like to know how to overwrite a file in python. When I'm using "w" in the open statement, I still get only one line in my output file.
article = open("article.txt", "w")
article.write(str(new_line))
article.close()
Can you tell me please how can I fix my problem?
If you are in fact looking to overwrite the file line by line, you'll have to do some additional work - since the only modes available are read ,write and append, neither of which actually do a line-by-line overwrite.
See if this is what you're looking for:
# Write some data to the file first.
with open('file.txt', 'w') as f:
for s in ['This\n', `is a\n`, `test\n`]:
f.write(s)
# The file now looks like this:
# file.txt
# >This
# >is a
# >test
# Now overwrite
new_lines = ['Some\n', 'New data\n']
with open('file.txt', 'a') as f:
# Get the previous contents
lines = f.readlines()
# Overwrite
for i in range(len(new_lines)):
f.write(new_lines[i])
if len(lines) > len(new_lines):
for i in range(len(new_lines), len(lines)):
f.write(lines[i])
As you can see, you first need to 'save' the contents of the file in a buffer (lines), and then replace that.
The reason for that is how the file modes work.
"overwrite" is a strange term; especially since you expect to see more than one line from the above code
I am guessing you mean something like "write beyond". The word for that would be "append' and you would want 'a' instead of 'w'.

Python, editing csv, writing issues

I've been trying to write a simple thing to manage projects. The thing I am stuck on is the editing function.
def edit_assignment():
check()
if os.path.exists(fdir):
list_assignment()
file = open(fdir,'r+')
list = file.readlines()
line_edit = int(raw_input('line to edit: '))
list[line_edit] = 'x'
new_list = "\r\n".join(list)
file.write(new_list)
file.close()
else:
print 'error'
That is the relevant portion.
When I run this, what happens is, instead of re writing the file, it sort of blends the two. I don't understand what I am doing incorrectly, any help would be appreciated.
you could do something like this:
if os.path.exists(fdir):
lines = open(fdir, "r").readlines()
line_no = int(raw_input("line: "))
lines[line_no] = "x"
open(fdir, "w").write("".join(lines))
else:
print "error"
You are opening your file using 'r+' for reading and writing. After reading the existing file all further write operations will happen at the position of the file pointer - and this is the end of the file. This is why you are getting the detected behavior.
Options:
open the file, read the lines, close the file, open the file for writing, write the lines, close the file
or
set the file pointer back to position 0 of the file (start) using fp.seek(0)

Not writing to file, even with f.close()

Edited my program - still having same issue
Also, the linked answer that was recommened is useless as it only tells you that you cannot modify a file in place and does not offer any good solution.
I have a file that has line numbers at the start of it. I wrote a python script to eliminate these line numbers. This is my second attempt at it and I am still having the same issues
First I open the file and save it to a variable to reuse later:
#Open for reading and save the file information to text
fin = open('test.txt','r')
text = fin.read()
fin.close
#Make modifications and write to new file
fout = open('test_new.txt','w')
for line in text:
whitespaceloc = line.find(' ')
newline = line[whitespaceloc:]
fout.write(newline)
fout.close()
I have also tried using the 'with' keyword with no luck,
When I open test_new.txt it is empty
What is going on here?
My advice on how to do this would be:
1) Read the file to a buffer:
with open('file.txt','r') as myfile:
lines=myfile.readlines()
2) Now close and overwrite the same file with any changes you want to do just as you did before:
with open('file.txt','w') as myfile:
for line in lines:
whitespaceloc = line.find(' ')
newline = line[whitespaceloc:]
myfile.write("%s" %newline)

Categories