python:将具有单个反斜杠路径的字符串行转换为csv

python:将具有单个反斜杠路径的字符串行转换为csv,python,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

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

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打开它,我会在列中看到双反斜杠:

尝试
myColumn=[s.replace('\\\','\\')替换myColumn中的s]
。这应该将双反斜杠(4个反斜杠文字)替换为单反斜杠(2个反斜杠文字)。

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("\\\\", "\\")))
或者,使用模块:

输出


假设
myColumn=[…
是对代码的引用,您没有带双反斜杠的字符串。您有带双反斜杠的字符串文本,Python将其理解为带单反斜杠的字符串。您在字符串文本中看到的双反斜杠实际上表示一个文本反斜杠,因此不需要转换。感谢nput。是的,我理解这一点,但为什么我的csv在列中有两个反斜杠?请参阅注释下的图片…然后将它们加倍,从而4个反斜杠。请解决您的问题。其中的代码需要执行您所说的操作,正如注释所指出的,它不会。@jonaswolf或使用原始字符串。
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))