python:cs中带有单反斜杠路径的字符串行

2024-09-29 01:21:27 发布

您现在位置: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


Tags: csvto字符串falseindexhereexcelgas
2条回答

试试myColumn = [s.replace('\\\\', '\\') for s in myColumn]。这应该将双反斜杠(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("\\\\", "\\")))

或者,使用^{}模块:

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

相关问题 更多 >