Clean from .txt, write new variable as a csv delimited string (not list) into a csv file
<p>my .txt file looks like the following:</p>

<pre><code>Page 1 of 49
&lt;=""&gt;
View Full Profile
S.S. Anne
Oil Tanker
42 miles offshore
Anchor length is 50 feet
&lt;=""&gt;
View Full Profile
S.S. Minnow
Passenger Ship
1502.2 miles offshore
Anchor length is 12 feet
&lt;=""&gt;
View Full Profile
S.S. Virginia
Passenger Ship
2 km offshore
Anchor length is 25 feet
&lt;=""&gt;
View Full Profile
S.S. Chesapeake
Naval Ship
10 miles offshore
Anchor length is 75 feet
&lt;=""&gt;
</code></pre>

<p>I've worked out the cleaning part so that following 'View Full Profile' I take the next 4 line items and put them into their own new line item, I do this for each instance of 'View Full Profile'.</p>

<p>Code:</p>

<pre><code>import csv 

data = []
with open('ship.txt','r',encoding='utf8') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if 'View Full Profile' in line:
            x = [lines[i+1],lines[i+2],lines[i+3],lines[i+4]]
            data.append(x)

for line in data:
    y = line
    print(y)

with open('ship_test.csv', 'w') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in data:
        writer.writerow(line)
</code></pre>

<p>And the output of printing y to see what will be written into the new file is:</p>

<pre><code>['S.S. Anne\n', 'Oil Tanker\n', '42 miles offshore\n', 'Anchor length is 50 feet\n']
['S.S. Minnow\n', 'Passenger Ship\n', '1502.2 miles offshore\n', 'Anchor length is 12 feet\n']
['S.S. Virginia\n', 'Passenger Ship\n', '2 km offshore\n', 'Anchor length is 25 feet\n']
['S.S. Chesapeake\n', 'Naval Ship\n', '10 miles offshore\n', 'Anchor length is 75 feet\n']
[Finished in 0.1s]
</code></pre>

<p>When it copies into the new file I get the following:</p>

<pre><code>"S.S. Anne
","Oil Tanker
","42 miles offshore
","Anchor length is 50 feet
"
"S.S. Minnow
","Passenger Ship
","1502.2 miles offshore
","Anchor length is 12 feet
"
"S.S. Virginia
","Passenger Ship
","2 km offshore
","Anchor length is 25 feet

"
"S.S. Chesapeake
","Naval Ship
","10 miles offshore
","Anchor length is 75 feet
"
</code></pre>

<p>I am looking to write into the new file the output of y. I believe it writes each item as its own line due to the '/n' attached to each element of x. How do I remove this (I tried splitting and received an error) so that x is written as a single line item in the new file as a csv string?</p>

<pre><code>line = line.replace('\n', '')
</code></pre>

<p>Use the replace method</p>

<p>If there is a list of strings:</p>

<pre><code>line = [l.replace('\n', '') for l in line]
</code></pre>

python csv