It reads the csv file from Python 3, with " at the end of the line and at the beginning.

Asked 2 years ago, Updated 2 years ago, 65 views

The goal is to read data row by row from an A.csv file, edit it, and save it to a B.csv file.

This is the same file as above, and the part shown is the third column. I tried to edit only the third column at a time with Python, but there was another problem, so I'm testing it with the other column erased on the Excel.

I want to separate several reports within one cell, remove the new line characters, and save them in file B.

[Number~Number] #Tag -> You want to delete this part.

Substation #Number~ -> Record this later part as a reference. This statement is not recorded.

Remove all -> line breaks and record them in file B as a single line.

The code we implemented for the above function is as follows.

import csv


originFile = open("test_min_data.csv", "r")
writeFile = open("01forwrting.csv", "w")

lines = originFile.readlines()
txt = []
for n in range(9999):
    txt.append([])
t_line=0
j=0
results = ['']
for n in range(9999):
    results.append('')


For i in range (100): # Error if you set the range to len(lines), error if you set it to number. Why? => Resolution: lines[j+1] in the while statement exceeds the line's index. Resolve the error stop with a try-exception statement.
    print(lines[i])
    '''
    If lines[i][0:5] == "Adas forest #": # When you meet the Adas forest report,
        j=i
        try:
            while (lines[j+1][0:5]! = "Adae Forest #"): #Stacking each line on txt until the next sentence is not an Adae Forest tip
                txt[t_line].append(lines[j+1])
                j+=1
            t_line+=1
        except:
            continue
    '''

Except for the annotated part, print(lines[i]) causes the following problems.

Like this picture, at the beginning of the line, at the end of the line, there's a "." Why is this happening?

python csv

2022-09-22 20:22

1 Answers

There is no problem with python code, it is a problem with the csv file.

If you read these csv files in this Python code,

f = open("filename.csv", "r")
lines = f.readlines()

for line in lines:
    print(line)

The results are as follows:

csv file

"line2-1
line2-2
line2-3"

It has double quotes, right? This is because the cell has an open letter. To resolve this, see Related questions .


2022-09-22 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.