从文件名

时间:2017-01-05 09:39:38

标签: python file

我有这段代码:

import sys
import os
import re
import fnmatch
import csv
import pandas as pd
import numpy as np
from dateutil.parser import parse as parseDate
from datetime import datetime, time, timedelta

file = open("0556_16-09-20114725356354 --- 16-12-2016 07-00-00.csv", 'r')
filename = os.path.splitext(os.path.basename(file))[0]
timestamp = filename[-19:]
print timestamp
date = timestamp[:10] + " " + timestamp[-8:].replace("-",":")
print date
newdatefile = parseDate(date, yearfirst=True)
print newdatefile

我的目标是从文件名中提取日期并解析它并将其保存在变量中。我想得到的是这样的:16-12-2016 07-00-00

这是我得到的错误:

Traceback (most recent call last):
  File "t.py", line 13, in <module>
    filename = os.path.splitext(os.path.basename(file))[0]
  File "/usr/lib/python2.7/posixpath.py", line 114, in basename
    i = p.rfind('/') + 1
AttributeError: 'file' object has no attribute 'rfind'

关于这可能是什么的任何想法?

2 个答案:

答案 0 :(得分:2)

Fatal error: Cannot redeclare wpb_getImageBySize() (previously declared in /home/likemedi/public_html/wp-content/themes/subway/wpbakery‌​/js_composer/compose‌​r/lib/helpers.php:15‌​) in /home/likemedi/public_html/wp-content/plugins/js_composer/in‌​clude/helpers/helper‌​s.php on line 114你在这里传递一个文件对象,而它需要一个字符串

答案 1 :(得分:1)

您无需os.path为您执行此操作。为什么不直接从您传递给open的参数中获取文件名:

filename = "0556_16-09-20114725356354 --- 16-12-2016 07-00-00.csv"
file = open(filename, 'r')