擅长:python、mysql、java
<p>除了@Joshua对for循环的观察之外,您还可以将该算法推广到较短的代码中。OP的代码中也可能有错误。<code>each_line[33]</code>被跳过。如果是故意的,下面的代码说明了原因:</p>
<pre><code>import csv
# starts for each column
cols = (0,1,34,35,43,51,62,64,89,114,122,123,134,159,184,185,193,199,202,211,
217,232,242,251,252,260,268,276,278,280,283,291,299,307,315,323,331,
339,347,355,363,364,365,366,367,376,378,380,382,384,387,389,400,411,
422,433,444,455,466,468,472,475,483,491,499,507,515,523,570,580,610,
665,720,735,737,746,784,785)
# newline='' per csv documentation.
with open('file.txt') as f, open('file.csv','w',newline='') as out_f:
writer = csv.writer(out_f)
for each_line in f:
line = []
for i in range(len(cols)-1):
# compute the slice for each column
start,end = cols[i],cols[i+1]
# This may be an error in OP's code, but each_line[33] is skipped.
if end == 34:
end = 33
line.append(each_line[start:end])
writer.writerow(line)
</code></pre>