[英]How to replace first number before a space in each line in a text file
My file look like the following:我的文件如下所示:
12.32 1:34 2:49 5:21 29:98
13.53 1:23 2:82 5:23 29:45
51.92 1:23 2:54 5:54 29:63
12.42 1:34 2:43 5:32 29:32
I am trying to replace every first number in each line by another number.我试图用另一个数字替换每行中的每个第一个数字。 So the output will be like
所以输出会像
21.33 1:34 2:49 5:21 29:98
16.23 1:23 2:82 5:23 29:45
93.12 1:23 2:54 5:54 29:63
18.76 1:34 2:43 5:32 29:32
What would be a good method?什么是好的方法?
I tried pointing to the number by我试着指向号码
with open('file.txt', 'r') as file:
line = file.readline()
line[0]
but it just gives me first character, not the entire number.但它只给了我第一个字符,而不是整个数字。 Thank you so much!
非常感谢!
You can use following method to achieve this:-您可以使用以下方法来实现这一点:-
data = None
with open('file.txt', 'r') as file:
data = file.read()
def process_line_item(x):
index = x[0]
line_str = x[1]
new_first_value = [str(x[0])] # you can put here new value depending on line index
return ' '.join(new_first_value + x[1].split(' ')[1:])
new_data = '\n'.join(list(map(process_line_item, enumerate(data.split('\n')))))
with open('new_file.txt', 'w') as file:
file.write(new_data)
file.txt
12.32 1:34 2:49 5:21 29:98
13.53 1:23 2:82 5:23 29:45
51.92 1:23 2:54 5:54 29:63
12.42 1:34 2:43 5:32 29:32
new_file.txt
0 1:34 2:49 5:21 29:98
1 1:23 2:82 5:23 29:45
2 1:23 2:54 5:54 29:63
3 1:34 2:43 5:32 29:32
you could use the csv
module with delimiter=" "
:您可以使用带有
delimiter=" "
的csv
模块:
from csv import reader
with open('file.txt', 'r') as file:
csv_reader = reader(file, delimiter=" ")
for row in csv_reader:
row[0] = '??.??'
print(row)
which outputs哪个输出
['??.??', '1:34', '2:49', '5:21', '29:98']
['??.??', '1:23', '2:82', '5:23', '29:45']
...
note that your numbers will be strings.请注意,您的数字将是字符串。 you may have to convert them to floats:
您可能需要将它们转换为浮点数:
floats = [float(item) for item in row]
if you then need to write the changes to a file you could similarly use a csv.writer
.如果您需要将更改写入文件,您可以类似地使用
csv.writer
。
This code should do the trick, however it may be a bit faulty and may need tweaking and testing a bit.这段代码应该可以解决问题,但是它可能有点错误,可能需要稍微调整和测试。 I hope it helps though.
我希望它有帮助。
with open('file.txt', 'r') as file:
file_content = file.read()
list_content = [letter for letter in file_content]
num_length = 0
for i, char in enumerate(list_content):
num_length += 1
if list_content[i - 1] == '\n':
num_length = 0
elif char == ' ':
start_index = i - num_length
for _ in range(num_length + 1):
list_content.pop(start_index)
list_content.insert(start_index, your_new_number)
out_text = ''.join(list_content)
with open('file.txt', 'w+') as file:
file.write(out_text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.