我有一个文本文件text.csv
,日期安排如下。
name1
2010-01-02 (i)
2010-05-07 (i)
2010-06-12 (i)
name2
2010-01-02 (i)
2010-05-07 (i)
2010-06-12 (i)
name3
2011-01-05 (i)
2011-05-05 (i)
2011-06-14 (i)
我想将文件重新格式化或写入2列,如:
+---------------+-----+
| 2010-01-02 (i)|name1|
| 2010-05-07 (i)|name1|
| 2010-06-12 (i)|name1|
| 2010-01-02 (i)|name2|
| 2010-05-07 (i)|name2|
| 2010-06-12 (i)|name2|
| 2011-01-05 (i)|name3|
| 2011-05-05 (i)|name3|
| 2011-06-14 (i)|name3|
+---------------+-----+
逻辑如下:
if line doesn't contain "(i)", name=value
else
write date=value, name to file
我宁愿不使用PHP,但我可以遍历数据:
<?php
$file = file($path);
foreach($file as $value)
{
if ( strpos($value, "(i)" ) !== false)
$name = $value;
$fp = fopen('data.csv', 'w');
fputcsv($fp, $line);
fclose($fp);
}
你能提供一个可以让我入门的python示例吗?它需要在Libre office calc。中作为一个宏运行。
答案 0 :(得分:2)
正如我在评论中所说,您的输入文件不是CSV文件。您可以使用以下命令进行所需的格式设置并生成有效的CSV文件。许多电子表格程序都可以读取使用逗号或制表符(&#39; \ t&#39;)作为分隔符的CSV文件。
import csv
DELIMITER = ','
with open('data.csv', 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=DELIMITER)
row = [None, None]
with open('input_data.txt', 'rt') as textfile:
for line in (line.strip() for line in textfile):
if line.endswith('(i)'):
row[0] = line
writer.writerow(row)
else:
row[1] = line
答案 1 :(得分:1)
data = '''name1
2010-01-02 (i)
2010-05-07 (i)
2010-06-12 (i)
name2
2010-01-02 (i)
2010-05-07 (i)
2010-06-12 (i)
name3
2011-01-05 (i)
2011-05-05 (i)
2011-06-14 (i)'''
name = None
for line in data.splitlines():
if '(i)' in line:
print line, name
else:
name = line
结果:
2010-01-02 (i) name1
2010-05-07 (i) name1
2010-06-12 (i) name1
2010-01-02 (i) name2
2010-05-07 (i) name2
2010-06-12 (i) name2
2011-01-05 (i) name3
2011-05-05 (i) name3
2011-06-14 (i) name3
现在你必须阅读文件并写行以代替print
。
答案 2 :(得分:1)
另一种相当简单的方法:
lines = []
with open('original.txt') as f:
for line in f:
if line.startswith('name'):
key = line.rstrip()
else:
lines.append('{} {}'.format(line.rstrip(), key))
with open('output.txt', 'w') as f:
f.writelines(lines)