Write a multi line string to a text file using Python - 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()

Related

How to write the result in text file?

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.

Add 1 word after readlines()

I am still learning python and have a question about the function readlines() The following is a part of my script:
f = open("demofile.txt", "r")
text = "".join(f.readlines())
print(text)
demofile.txt contains:
This is the first line
This is the second line
This is the third line
Now I want to add a single word to this so I get:
This is the first line
This is the second line
This is the third line
Example
I thought of something easy way of doing it:
f = open("demofile.txt", "r")
text = "".join(f.readlines())."Example"
print(text)
But that doesn't work (of course) I googled and looked around here but didn't really have the good keywords to search for this issue. Hopefully someone can point me in the right direction.
.readlines() returns list you can append() to it:
with open("demofile.txt") as txt:
lines = txt.readlines()
lines.append("Example")
text = "".join(lines)
print(text)
or you can unpack the file object txt, since its an iterator to a new list with the word you wanted to add:
with open("demofile.txt") as txt:
text = "".join([*txt, "Example"])
print(text)
Firstly, the open function in python opens a file in read mode by default. Thus, you do not need to specify the mode r when opening the file. Secondly, you should always close a file after you are done with it. A with statement in python handles this for you. Moreover, instead of using . to add Example onto the end of the string, you should use the concatenation operator in python to add a newline character, \n, and the string, Example.
with open("demofile.txt") as f:
text = "".join(f.readlines()) + "\nExample"
print(text)
This should help you. While dealing with files. It is always recommended to use with open('filename','r') as f instead of f=open('filename','r'). Using ContextManager during file open is the idea that this file will be open in any case whether everything is ok or any exception is raised. And you don't need to explicitly close the file i.e f.close().
end_text='Example'
with open('test.txt','r') as f:
text=''.join(f.readlines())+'\n'+end_text
print(text)

How to read a file and write it entirely to several text files using Python?

I want to load/read a text file and write it to two other text files "entirely". I will write other different data to the following of these two files later.
The problem is that the loaded file is only written to the first file, and no data from that loaded file is written to the second file.
The code I am using:
fin = open("File_Read", 'r')
fout1 = open("File_Write1", 'w')
fout2 = open("File_Write2", 'w')
fout1.write(fin.read())
fout2.write(fin.read()) #Nothing is written here!
fin.close()
fout1.close()
fout2.close()
What is happening and what is the solution?
I prefer using open instead of with open.
Thanks.
Apparently the fin.read() reads all the lines, the next fin.read() will continue from where the previous .read() ended (which is the last line). To solve this, I would simply go for:
text_fin = fin.read()
fout1.write(text_fin)
fout2.write(text_fin)
fin = open("test.txt", 'r')
data = fin.read()
fin.close()
fout1 = open("test2.txt", 'w')
fout1.write(data)
fout1.close()
fout2 = open("test3.txt", 'w')
fout2.write(data)
fout2.close()
N.B. with open is the safest and best way but at least you need to close the file as soon as there are not needed anymore.
You can try iterating through your original file line by line and appending it to both the files. You are running into the problem because file.write() method takes string argument.
fin = open("File_Read",'r')
fout1 = open("File_Write1",'a') #append permissions for line-by-line writing
fout2 = open("File_Write2",'a') #append permissions for line-by-line writing
for lines in fin:
fout1.write(lines)
fout2.write(lines)
fin.close()
fout1.close()
fout2.close()
*** NOTE: Not the most efficient solution.

The following code is supposed to read a file and print the file contents to the Terminal window. It doesn’t work, I'm not sure why?

The following code is supposed to read a file and print the file contents to the Terminal window. It doesn’t work, I'm not sure why?
filename = raw_input(’Provide the path to a text file: ’)
txt = open(filename)
print txt
First, you need to use straight quotes ' instead of smart quotes ’. Second, you need to actually read the opened file with something like read().
filename = raw_input('Provide the path to a text file: ')
txt = open(filename).read()
print txt

Editorial iOS : Remove first characters in each line

I'm trying to create an Editorial workflow to remove the six first characters of each line in a file.
For now, I've builded a new worklfow composed by three steps :
Get selected text
Custom Python script
Replace selected text
My Python script is :
#coding: utf-8
import workflow
action_in = workflow.get_input()
text = open("temp.txt", "w+")
text.write(action_in)
lines = text.readlines()
for line in lines:
text.write(line[6:])
action_out = text.read()
workflow.set_output(action_out)
Actually, when I try to use this workflow on a line, it just erases it.
How should I do?
Thank you in advance.
I suspect the issue is that you need to close “temp.txt” and then re-open it. This works for me:
import workflow
action_in = workflow.get_input()
text = open("temp.txt", "w+")
text.write(action_in)
text.close()
text = open("temp.txt", "r")
lines = text.readlines()
text.close()
text = open("temp.txt", "w+")
for line in lines:
text.write(line[6:])
text.close()
text = open("temp.txt", "r")
action_out = text.read()
workflow.set_output(action_out)
The “w+” in your initial “open” statement erases the file and opens it for read/write; however, the file pointer will follow the write. The safest method is to close the file when done, and re-open it to reset the file pointer and get the data you want.
Since you’re using w+, you might also be able to use .seek() to reposition the file pointer, depending on caching, however, if your outline is all you need, there’s no need to open a temporary file to perform this action.
import workflow
action_in = workflow.get_input()
lines = []
for line in action_in.split("\n"):
lines.append(line[6:])
action_out = "\n".join(lines)
workflow.set_output(action_out)

Categories