[英]How to write a string at a specific line of a plain text file using Racket language?
我是 Racket 語言的新手,我不知道如何在純文本文件的特定行寫入字符串(新行)。
我已經看到append過程完成在文件末尾插入新行的工作。
此外,Racket 文檔討論了Counting Positions, Lines, and Columns ,但是我發現沒有容易理解的例子(至少對我而言)。
一個例子可以更好地說明我想要什么。
假設一個文件(稱為test.txt
)有 10 行,我必須寫一個字符串" New information starts here."
在第 7 行和第 8 行之間。
我的意思是在成功插入新行后, test.txt
文件將有 11 行。
任何幫助我將不勝感激。 最好的事物。
最簡單的就是復制舊文件,復制時插入新行。 然后刪除舊文件並將新文件重命名為舊文件名。
可以按如下方式進行復制:
#lang racket
; insert-line : string number ->
; Almost copies line for line the current input port to the current output port.
; When line-number lines have been copied an extra line is inserted.
(define (insert-line line line-number)
(for ([l (in-lines)]
[i (in-naturals)])
(when (= i line-number)
(displayln line))
(displayln l)))
; insert-line-in-file : file file string number ->
; copies file-in to file-out and inserts the line line at the given line number.
(define (insert-line-in-file file-in file-out line line-number)
(with-outout-to-file file-out
(λ ()
(with-input-from-file file-in
(λ ()
(insert-line line line-number))))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.