简体   繁体   English

如果字符串包含在文件名中,则将值添加到列中(python 3)

[英]If string contains in filename, then add value to column (python 3)

I'm trying to add a month column with values to an existing Excel-File (xlsx). 我正在尝试将具有值的月份列添加到现有的Excel文件(xlsx)。 With the if statement, it's supposed to add a specific month based on the string in the file name. 使用if语句,应该根据文件名中的字符串添加特定的月份。 Despite not receiving an error, my function seems to have problem looking up the filename (it works however if I do something like 'if "jan" in "monthjanmonth"). 尽管没有收到错误,但是我的函数似乎在查找文件名时遇到了问题(但是,如果我在“ monthjanmonth”中执行“ if”“ jan”之类的操作,它就可以工作)。

sale14_file = pd.read_excel("sales-jan-2014.xlsx")
File_Name = glob.glob("sales-jan-2014.xlsx")

# adding date as first column
def AddingDate():
    if "jan" in File_Name:
        CustomMonth = "January"
        sale14_file.insert(0, "Date", CustomMonth)

AddingDate()

IDE: pycharm IDE:pycharm

Python version: 3.0 Python版本:3.0

Windows 7 Windows 7的

Just figured out the answer myself. 我自己才想出答案。 Had to add "str" to the filename variable. 必须在文件名变量中添加“ str”。

File_Name = str(glob.glob("sales-jan-2014.xlsx"))

instead 代替

File_Name = glob.glob("sales-jan-2014.xlsx")
file_handler = open('sales-jan-2014.xlsx','w')
file_handler.close()

File_Name = glob.glob("sales-jan-2014.xlsx")
type(File_Name)
print('{0}'.format(File_Name))


x = "jan" in File_Name
print('{0}'.format(x))

x = "jan" in str(File_Name)
print('{0}'.format(x))

x = "jan" in File_Name[0]
print('{0}'.format(x))

result 结果

['sales-jan-2014.xlsx']
False
True
True

This is a list :) you need to use str() or change your code 这是一个列表:),您需要使用str()或更改代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM