[英]Python writing a range loop with multiple rows
我正在嘗試編寫一個腳本來根據循環中的范圍即nums = range(17501, 17570)
增加幾行的第二列。 因此,在每次增量時,第二列中的所有值都將increment to 17202 and then 17203
等,其余部分保持不變,有什么建議嗎?
數據已經在一個文件中,所以我需要某種形式的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
感謝 ROCKLY LI 我得到了這個工作。 唯一的問題是它需要按上面的數字排序,也許按第 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')
我認為與其就地編輯文件,不如生成一個新文件並保留舊文件更合理,而且使用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=' ')
就是這樣。
沒有熊貓,你可以這樣做:
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.