我正在读取CSV文件,并打算写入Excel文件。CSV文件只有两列,但是在写入Excel之前,我想使用regex提取列数据并创建新列
CSV文件:test.csv
name, file_info
test, c:\folder1\subfolder1\subfolder2\example.xls | history 12345 at 2020-01-01
以下是我目前掌握的代码:
import csv
with open('test.csv',mode='r') as testFile
reader = csv.DictReader(testFile, delimiter=',')
for row in reader:
### This is where i assume i need to perform the regex operation on the current row
我想将文件名(example.xlsx
)、历史记录(12345
)和日期(2020-01-01
)提取为Excel文件中的列
我成功地测试了正则表达式
"\\([^\\|]*)\s*\|\"
我相信有多种方法可以做到这一点。熊猫会更好吗?我可以通过以下方式简单地将文件读写到excel:
df = pd.read_csv('test.csv')
df.to_excel('text.xlsx)
我没有任何熊猫的经验,所以不知道如何使用regex执行我想要的操作,并将其连接在一起
最终产品是具有五(5)列的excel电子表格
name | path | file | history | date
下面是一种使用Pandas
df['column'].str.extract()
函数的技术您可以将已编译(或未编译)的正则表达式字符串传递到
extract()
函数中。这将使用表达式中的命名组,并将这些组提取到具有相同名称的列中样本数据:
代码:
Excel输出:
相关问题 更多 >
编程相关推荐