python:带有单反斜杠路径的字符串行进入csv

时间:2018-09-13 04:48:34

标签: python

如何转换带有双反斜杠的字符串行:

myColumn =
['hot\\gas\\substance\\1',
'hot\\gas\\substance\\2',
'hot\\gas\\substance\\3']

插入带有单反斜杠的字符串行中:

myColumn=
['hot\gas\substance\1',
'hot\gas\substance\2',
'hot\gas\substance\3']

并将myColumn保存为csv:

myColumn.to_csv(exportPath +'/myColumnNEW.csv', index=False)

谢谢

注意 如果将myColumn保存在.csv中并用Excel打开它,我会在该列中看到双反斜杠: here is the screenshot of output

2 个答案:

答案 0 :(得分:1)

尝试myColumn = [s.replace('\\\\', '\\') for s in myColumn]。这应该用单反斜杠(2个反斜杠文本)替换双反斜杠(4个反斜杠文本)。

答案 1 :(得分:0)

给出

import csv
import pathlib


my_column = [
    "hot\\\\gas\\\\substance\\\\1",
    "hot\\\\gas\\\\substance\\\\2",
    "hot\\\\gas\\\\substance\\\\3"
]

filepath = "test.csv"

代码

with open(filepath, "w", newline="\n") as f:
    writer = csv.writer(f)
    header = ["Count", "Subfolder"]
    writer.writerow(header)
    for i, s in enumerate(my_column):
        writer.writerow((i, s.replace("\\\\", "\\")))

或者,使用pathlib模块:

with open(filepath, "w", newline="\n") as f:
    writer = csv.writer(f)
    header = ["Count", "Subfolder"]
    writer.writerow(header)
    for i, s in enumerate(my_column):
        path = pathlib.PureWindowsPath(s)
        writer.writerow((i, path))

输出

enter image description here