为什么该文件名上的前导字符意外地被strip()剥离了?

时间:2019-06-03 03:46:29

标签: python python-3.x

我正在通过使用Python自动完成无聊的事情的工作。我刚刚使该项目正常工作(使用Openpyxl从工作表中获取数据并将其放入CSV文件中)。唯一的意外行为是我的文件名不完全符合我的期望。电子表格文件名由作者提供为示例文件。它们采用“ spreadsheet-A.xlsx”的形式。无需返回我的预期文件名,strip()会删除开头的“ s”。

这没什么大不了的,但是我很好奇为什么会这样,而且我还没有弄清楚。

预期的行为:spreadsheet-A.xlsx变成spreadsheet-A.csv 实际行为:spreadsheet-A.xlsx变成preadsheet-A.csv

我的猜测是问题出在第20和21行,并且我不知道脱衣舞有些问题。

#!/usr/bin/python

# excelToCSV.py - Converts all excel files in a directory to CSV, one file
# per sheet

import openpyxl
from openpyxl.utils import get_column_letter
import csv
import os

for excelFile in os.listdir('.'):
    #Skip non-xlsx files, load the workbook object.
    if excelFile.endswith('.xlsx'):
        wbA = openpyxl.load_workbook(excelFile)
        #Loop through each sheet in the workbook
        for sheet in wbA.worksheets:    
            sheetName = sheet.title
            sheetA = wbA.get_sheet_by_name(sheetName)
            # Create the CSV filename from the excel filename and sheet title
            excelFileStripped = excelFile.strip('.xlsx')
            csvFilename = excelFileStripped + '.csv'
            # Create the csv.writer object for this csv file
            csvFile = open(csvFilename, 'w', newline='')
            csvWriter = csv.writer(csvFile)
            # Loop through every row in the sheet
            maxRow = sheetA.max_row
            maxCol = sheetA.max_column
            for rowNum in range(1, maxRow + 1):
                rowData = []
                # Loop through each cell in the row
                for colNum in range(1, maxCol + 1):
                    # Append each cell's data to rowData
                    x = get_column_letter(colNum)
                    coordinate = str(x) + str(rowNum)
                    cellA = sheetA[coordinate]
                    #cellValue = cellA.value 
                    rowData.append(cellA.value)
                    # Write the rowData list to the csv file
                csvWriter.writerow(rowData)

            csvFile.close()

    else:
        continue

2 个答案:

答案 0 :(得分:3)

如注释中所述,strip实际上是对单个字符(长度为1的字符串)进行迭代,并从字符串的开头和结尾删除其中任何一个的所有实例(文档here )。

虽然可以使用rstrip,但是我建议使用os中专门用于处理路径的功能,例如:

import os

print(os.path.splitext('my_file.xlsx'))

输出:

('my_file', '.xlsx')

将此应用于您的代码,您可能会得到以下信息:

for filename in os.listdir(os.curdir):
    name, extension = os.path.splitext(filename)
    if extension == '.xlsx':
        # Excel file: do stuff...

答案 1 :(得分:0)

摆脱结局的另一种方法可能是:

ending = ".csv"
txt = "Hello, my name is H.xlsx"
sep = '.'
rest = txt.split(sep, 1)[0]
new = rest+ending

这将删除结束部分并添加结束变量。

相关问题