[英]Python writing a range loop with multiple rows
I'm trying write a script to increment the second column of several rows based on a range in loop ie nums = range(17501, 17570)
.我正在尝试编写一个脚本来根据循环中的范围即
nums = range(17501, 17570)
增加几行的第二列。 So on each increment the all values in the second column will increment to 17202 and then 17203
etc leaving the rest intact , any suggestions?因此,在每次增量时,第二列中的所有值都将
increment to 17202 and then 17203
等,其余部分保持不变,有什么建议吗?
The data is already in a file so I need some form of read
and then write
the ouput, is this even possible ?数据已经在一个文件中,所以我需要某种形式的
read
然后write
输出,这甚至可能吗?
x1E 17201 18 0 1 0 0 1
x2E 17201 19 0 1 0 0 1
x3E 17201 20 0 1 0 0 1
x4E 17201 21 0 1 0 0 1
x5E 17201 22 0 1 0 0 1
x6X 17201 23 0 1 0 0 1
x7X 17201 24 0 1 0 0 1
x8X 17201 25 0 1 0 0 1
x9X 17201 26 0 1 0 0 1
10X 17201 27 0 1 0 0 1
11X 17201 28 0 1 0 0 1
12X 17201 29 0 1 0 0 1
13X 17201 30 0 1 0 0 1
14X 17201 31 0 1 0 0 1
15X 17201 32 0 1 0 0 1
16X 17201 33 0 1 0 0 1
20X 17201 34 0 1 0 0 1
17X 17201 35 0 1 0 0 1
18X 17201 36 0 1 0 0 1
19X 17201 37 0 1 0 0 1
Thanks to ROCKLY LI I got this to work.感谢 ROCKLY LI 我得到了这个工作。 Only problem it needs sorting as above perhaps by the 3 rd column numerically , how to sort the written output in the file ?
唯一的问题是它需要按上面的数字排序,也许按第 3 列排序,如何对文件中的写入输出进行排序?
nums = range(17201,17920)
with open('Orig.txt', 'r') as fin:
with open('PLF.txt', 'w') as fout:
for line in fin.readlines():
line = line.split()
#if 17200 < int(line[1]) < 17920:
#print(line)
for i in range(0, len(nums),):
line[1] = int(line[1]) + 1
#line.append(str(line[1] + 1))
line = [str(e) for e in line] # Fix type
print(line)
#fout.write(' '.join(line) + '\n')
fout.write(' '.join(line) + '\n')
I think instead of editing the file in place, it's more reasonable to generate a new one and keep the old one, and it's incredibly easy with pandas
我认为与其就地编辑文件,不如生成一个新文件并保留旧文件更合理,而且使用
pandas
非常容易
import pandas as pd
df = pd.read_table('your_file.txt', header=None, delim_whitespace=True)
df[1] = df.apply(lambda x: x[1] + 1 if 17501 <= x[1] < 17570 else x[1])
df.to_csv('new_file.txt', sep=' ')
And that's it.就是这样。
Without pandas, you can do:没有熊猫,你可以这样做:
with open('your_file.txt', 'r') as fin:
with open('new_file.txt', 'w') as fout:
for line in fin.readlines():
line = line.split()
if 17000 < int(line[1]) < 18000:
line[1] = int(line[1]) + 1
line = [str(e) for e in line] # Fix type
fout.write(' '.join(line) + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.