파일 시작 부분에 줄 추가
별도의 파일을 사용하여이 작업을 수행 할 수 있지만 파일 시작 부분에 줄을 어떻게 추가합니까?
f=open('log.txt','a')
f.seek(0) #get to the first position
f.write("text")
f.close()
파일이 추가 모드에서 열리기 때문에 파일 끝부터 쓰기가 시작됩니다.
모드 'a'또는 에서는 함수가 트리거 된 'a+'현재 순간 write()에 파일의 포인터가 파일의 끝에 있지 않더라도 파일의 끝에서 쓰기가 수행 됩니다. 포인터가 쓰기 전에 파일의 끝으로 이동합니다. . 두 가지 방식으로 원하는 것을 할 수 있습니다.
첫 번째 방법 은 파일을 메모리에로드하는 데 문제가없는 경우 사용할 수 있습니다.
def line_prepender(filename, line):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
두 번째 방법 :
def line_pre_adder(filename, line_to_prepend):
f = fileinput.input(filename, inplace=1)
for xline in f:
if f.isfirstline():
print line_to_prepend.rstrip('\r\n') + '\n' + xline,
else:
print xline,
이 방법이 내부에서 어떻게 작동하는지, 그리고 그것이 큰 파일에 사용될 수 있는지는 모르겠습니다. 입력에 전달 된 인수 1은 한 줄을 제자리에 다시 쓸 수있게합니다. 내부 작업이 발생하려면 다음 줄을 앞뒤로 이동해야하지만 메커니즘을 모르겠습니다.
내가 익숙한 모든 파일 시스템에서는이 작업을 제자리에서 수행 할 수 없습니다. 보조 파일을 사용해야합니다 (원래 파일의 이름을 사용하도록 이름을 바꿀 수 있음).
NPE의 답변에 코드를 넣으려면 가장 효율적인 방법은 다음과 같습니다.
def insert(originalfile,string):
with open(originalfile,'r') as f:
with open('newfile.txt','w') as f2:
f2.write(string)
f2.write(f.read())
os.rename('newfile.txt',originalfile)
다른 아이디어 :
(1) 원본 파일을 변수로 저장합니다.
(2) 원본 파일을 새 정보로 덮어 씁니다.
(3) 새 정보 아래의 데이터에 원본 파일을 추가합니다.
암호:
with open(<filename>,'r') as contents:
save = contents.read()
with open(<filename>,'w') as contents:
contents.write(< New Information >)
with open(<filename>,'a') as contents:
contents.write(save)
There's no way to do this with any built-in functions, because it would be terribly inefficient. You'd need to shift the existing contents of the file down each time you add a line at the front.
There's a Unix/Linux utility tail which can read from the end of a file. Perhaps you can find that useful in your application.
num = [1, 2, 3] #List containing Integers
with open("ex3.txt", 'r+') as file:
readcontent = file.read() # store the read value of exe.txt into
# readcontent
file.seek(0, 0) #Takes the cursor to top line
for i in num: # writing content of list One by One.
file.write(str(i) + "\n") #convert int to str since write() deals
# with str
file.write(readcontent) #after content of string are written, I return
#back content that were in the file
The clear way to do this is as follows if you do not mind writing the file again
with open("a.txt", 'r+') as fp:
lines = fp.readlines() # lines is list of line, each element '...\n'
lines.insert(0, one_line) # you can use any index if you know the line index
fp.seek(0) # file pointer locates at the beginning to write the whole file again
fp.writelines(lines) # write whole lists again to the same file
Note that this is not in-place replacement. It's writing a file again.
In summary, you read a file and save it to a list and modify the list and write the list again to a new file with the same filename.
참고URL : https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file
'Program Club' 카테고리의 다른 글
| git fetch 이해 후 병합 (0) | 2020.12.07 |
|---|---|
| Javascript 변수를 선언 할 때 var가 필요합니까? (0) | 2020.12.07 |
| 빈 셀을 "NA"로 변경 (0) | 2020.12.06 |
| iOS 8에서 NSMutableAttributedString을 사용하는 문자열의 밑줄 부분이 작동하지 않습니다. (0) | 2020.12.06 |
| Nodemon으로 시작 스크립트를 실행하는 방법은 무엇입니까? (0) | 2020.12.06 |