[英]How to edit a text file?
我正在嘗試在python 3.7中編輯文本文件。 基本上,我有一個文本文件(file_1.txt),其中包含數字-像這樣一個3列5行
1, 10, 20
2, 20, 30
3, 30, 50
4, 35, 60
5, 50, 100
我想編輯該文件以便獲得一些不同之處,基本上這是
1, 10, 20
2, 20, 30
3, 30, 50
4, 35, 60
5, 50, 100
6, 10, 20
7, 20, 30
8, 30, 50
9, 35, 60
10, 50, 100
復制第二和第三列,第一列以數字繼續,每行增加一個。 我試圖這樣做,但是沒有成功。 這是我嘗試過的:
with open("file_1.txt", "r+") as file1:
file1.read()
i = 6
imax = 10
while i <= imax:
sentence = str(i) + "\n"
file1.write(sentence)
i = i + 1
我不明白如何復制第二列和第三列。
有誰知道如何做到這一點?
如果這是一個類似於csv的文件,則可能要使用pandas(這是處理數據框的最佳方法之一)。 一個簡單的例子:
import pandas as pd
df = pd.read_csv("<path_to_data_file>", header=None)
df = pd.concat([df, df])
df[0] = list(range(1, 11))
df.to_csv("result.csv", header=None, index=None)
Pythonic-way:它將換行符添加到文件中。
with open('sample.txt', 'r') as f:
l = [i.strip() for i in f.readlines()]
max_row = int(l[-1].split(',')[0])
x = [str(i) for i in range(max_row+1,11)]
y = [i.split(',', 1)[-1] for i in l]
with open('sample.txt', 'a') as f:
for item in [x[i]+',' + y[i] for i in range(len(x))]:
f.write("%s\n" % item)
PS:最大行數可以是行數的長度
簡短易行。 只需3行。
with open('file_1.txt', 'r+') as f:
for num, content in enumerate(f.readlines()):
f.write(f'{num+6}, {content[3:]}')
其他方式:
with open("test.txt", "r+") as file1:
lines = file1.readlines()
index = 0
i = 6
imax = 10
while i <= imax:
sentence = lines[index].split(", ")[1:]
sentence.insert(0, str(i))
file1.write(", ".join(sentence))
i += 1
index += 1
輸出:
1, 10, 20
2, 20, 30
3, 30, 50
4, 35, 60
5, 50, 100
6, 10, 20
7, 20, 30
8, 30, 50
9, 35, 60
10, 50, 100
首先,您需要從輸入中讀取所有數據,並將其存儲。
然后再次遍歷並將其寫入文件。
data = []
with open("file_1.txt", "r+") as file1:
# read the data
for line in file1:
# .strip() to remove the newline
# .split(", ") to split into 3 values
# map(int, ...) to convert each from string to integer
index, column2, column3 = map(int, line.strip().split(", "))
#save the second and third coluumn
data.append((column2, column3))
# now write it back again:
for column2, column3 in data:
index += 1 # continue incrementing the index
# format the lines and write them into the file
file1.write("{}, {}, {}\n".format(index, column2, column3))
這種方法直接將每一行作為一個字符串工作,而不用拆分多余的列。
第一個for循環將Cols 2&3(以逗號開頭)擴展為List,以跟蹤行數。 第二個循環從計數開始附加此列表遞增索引。
with open("file_1.txt", "r+") as file1:
our_data = []
count = 0
for line in file1:
first_comma_pos = line.find(',')
# extract cols 2&3 including the leading comma
our_data.append(line[first_comma_pos:])
count += 1
for i in range(count):
sentence = str(i + count) + our_data[i] + '\n'
file1.write(sentence)
下面的腳本將構建新文件,您可以設置要創建的行數。
首先從輸入文件中讀取所有行,然后將您設置的行數寫入新文件。
list_emitter
可以無限地產生給定列表中的項目,因此您只需調整output_lines_count
變量即可使輸出文件更大。
def list_emitter(l):
"""This generator will endlessly yield items from given list."""
while True:
for item in l:
yield item
with open('file_1.txt') as input_file:
lines = input_file.readlines() # Create list of lines
with open('output_file.txt', 'w') as output_file:
output_lines_count = 10 # Set how many output lines you want
for counter, line in enumerate(list_emitter(lines)):
if counter == output_lines_count:
break
first, second, third = line.strip().split() # Parse line
output_file.write('{}, {} {}\n'.format(counter+1, second, third))
該模塊也可以工作:
def edit(nrows, filename):
nrows +=1 #to avoid off-by-one error because dealing with lists
outf = open(filename, 'a')
column_1 = [1, 2, 3, 4, 5]
column_2 = [10, 20, 30, 35, 50]
column_3 = [20, 30, 50, 60, 100]
last_column_1 = column_1[-1]
list_1 = list(range(last_column_1+1, last_column_1+nrows))
list_2 = nrows//len(column_2)*column_2 + column_2[0:nrows%len(column_2)]
list_3 = nrows//len(column_3)*column_3 + column_3[0:nrows%len(column_3)]
for c1, c2, c3 in zip(list_1, list_2, list_3):
outf.write("{}, {}, {}\n".format(c1, c2, c3))
if __name__ == '__main__':
edit(10, 'file.txt')
假設有一個包含文本的file.txt
:
1, 10, 20
2, 20, 30
3, 30, 50
4, 35, 60
5, 50, 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.