所以我写了这段代码:
import csv
data = []
filename = "S:\Doc\Python\Data\Dekomp\Hth.txt"
with open(filename) as f:
lines = f.readlines()
for line in lines:
if line.startswith('%'):
data.append(line.split('+')[0].strip())
if line.endswith('%'):
break
with open('S:\Doc\Python\Data\Dekomp\Test.csv', 'w') as f:
writer = csv.writer(f, delimiter=' ')
for line in data:
writer.writerow(line.split())
我的数据如下:
标题从“%th = number”开始,而数字从2更改为180(每个段加2,所以变为(2、4、6 ...直到180)。
在这些段之间,我有三列数据,我想将它们附加到一个csv文件中。在使用我的代码时,我只保存了标题(%th = 2,%th = 4 ...%th = 180)。您有任何想法如何更改代码,以便它将开始读取标题,然后将下面的数据附加到.txt或.csv文件中,然后在“看到”另一个标题时再次开始循环,并继续保存下一段到另一个文件,直到“%th = 180”?
预期输出:
该程序会将“%th = number”以下的所有数据附加到另一个文件,然后在出现以下段时将其保存到另一个文件,并且该过程将继续到该文件结束。 换句话说,每个段都以偶数开头(2、4、6、8 ... 180),所以我应该得到90个文件,每个段都为一个文件。
更新2:
所以我更改了代码:
with open("S:\Doc\Python\Data\Dekomp\Hth.txt", 'r') as f:
with open("S:\Doc\Python\Data\Dekomp\Hth2.txt", 'w') as g:
for line in f:
if line.startswith("%"):
g.write(line)
if line.endswith("%"):
break
但是现在的问题是,如果我放置这个startswith
和endswith
python将仅保存标题,如果删除它们,这很明显,那么它将保存输入文件中的所有内容。
答案 0 :(得分:1)
data = []
filename = "S:\Doc\Python\Data\Dekomp\Hth.txt"
with open(filename) as f:
lines = f.readlines() # Reading file
def _get_all_starting_index(data): # Calculating index of all lines starting with %
return [data.index(line) for line in data if line.startswith("%")]
indices= _get_all_starting_index(lines)
data_info_to_write_in_file = {} # for storing data to write in each individual file
for i in range(len(indices)): # looping over number of indices
key = lines[indices[i]] # key value for starting of a segment.
end_point = indices[i+1] if len(indices) > i+1 else len(indices) # finding end point.
lines_to_get = lines[indices[i]+1 : end_point] # getting lines in between and storing it in dictionary
data_info_to_write_in_file[key] = lines_to_get
for key in data_info_to_write_in_file.keys(): # writing info in each individual file
filename = "S:\Doc\Python\Data\Dekomp\{}.txt".format(key.strip().split("=")[-1])
with open(filename, 'w') as f:
for line in data_info_to_write_in_file[key]:
f.write(line)
希望它会有所帮助。 随时获取任何信息。