Harley Harley - 8 months ago 81
Python Question

How to write a code into a .txt file with Python?

I have got a Python code, what i want to write into a .txt file, but I always get format error (because of the structure). How can I do this output in the correct form?I used # to see where start and end my "string" part.

Here what I tried:

#!/usr/bin/python
#!/bin/sh
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from selenium import webdriver
import urllib2
import subprocess
import unicodecsv as csv
import os
import sys
import io

array = ['link1', 'link2', 'link3']

string = #MY STRING IS START HERE
("browser = webdriver.Firefox()
datatable=[]
browser.get('%s') WebDriverWait(browser, 5).until(lambda s: s.execute_script("return jQuery.active==0"))
time.sleep(5)
html = browser.page_source
soup=BeautifulSoup(html,"html.parser")
\n")
#AND MY STRING END HERE

file="/Users/Adam/Desktop/data.txt"

with open(file, "w") as f:
for i in array:
f.write(string % i)

f.close()


EDIT:

string2= """query = """ load data local infile '/usr/src/Python-2.7.13/output.csv'
into table ARRIVALS
fields terminated by ';'
enclosed by '"'
lines terminated by '\n'
ignore 1 lines;
""" """

Answer Source

In order to write string over several lines, You must use triple-quotes, instead of single ones.

My guess is that your code will break here:

string = #MY STRING IS START HERE
("browser = webdriver.Firefox()
datatable=[]
   browser.get('%s')  WebDriverWait(browser, 5).until(lambda s: s.execute_script("return jQuery.active==0"))
time.sleep(5)
html = browser.page_source
soup=BeautifulSoup(html,"html.parser")
 \n")

because it can't read string this way.

Using

string = """browser = webdriver.Firefox()
datatable=[]
browser.get('%s')  WebDriverWait(browser, 5).until(lambda s: s.execute_script("return jQuery.active==0"))
time.sleep(5)
html = browser.page_source
soup=BeautifulSoup(html,"html.parser")
\n""")

should fix the issue.

For edited question: You should replace double-quotes in the string with escape code.

So, instead of

string = """ some text """ here """ """

You should use

string = """ some text \"\"\" here \"\"\" """
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download