1

When I am opening CSV file in excel or numbers, I am getting \r\n. I want to remove these. How to remove that?

Below is the example of the content. I want to remove all \r\n', '\n'.

a national security risk.\r\n', '\n', '\r\n Company executives inaugurated the Huawei European Cybersecurity Center, which will allow the wireless companies that are its customers to review the source code running its network gear.\r\n', '\n', "\r\n The launch comes amid a standoff between the U.S. and China over Huawei Technologies, the world's biggest maker of telecom infrastructure for new high-speed 5G networks.\r\n", '\n', "\r\n The U.S. has been lobbying allies to shun Huawei because of fears its equipment could facilitate digital espionage by China's communist leaders.\r\n", '\n', "\r\n The new lab in the Belgian capital gives Huawei a venue to reassure the EU's policymakers about its cybersecurity credentials.\r\n", '\n', '\r\n

import csv

with open('test.csv',newline='') as fin:
    with open('test1.csv','w',newline='') as fout:
        r = csv.reader(fin)
        w = csv.writer(fout)
        for row in r:
            row = [col.replace('\r\n','') for col in row]
            w.writerow(row)

When I tried the code, I just got another CSV​ file with test1 name. But it is same as test file.

Piyush Ghasiya
  • 515
  • 7
  • 25
  • If you'll remove all these symbols you'll get one-line CSV file. Is that what you want? – Alderven Apr 05 '19 at 10:00
  • I will open this CSV file in excel or numbers. So, I think it doesn't matter whether I will get one-line CSV file or not. As I am a beginner in python, please tell me the best solution to this problem. – Piyush Ghasiya Apr 06 '19 at 11:42

1 Answers1

-1

I just encounter the similar problem. Actually, in your csv file, '\n' or '\r\n' are actually presented by '\\n' and '\\r\\n' . Therefore, you should just replace '\n' by what you want. That's done.

Solution here .How to input a regex in replace function.

You might don't understand what I mean. just look at this

chickensoup
  • 334
  • 1
  • 17