파이썬을 사용하여 텍스트 파일에서 특정 행을 삭제하는 방법은 무엇입니까?
제가 닉네임으로 가득 찬 텍스트 파일을 가지고 있다고 가정해 보겠습니다.파이썬을 사용하여 이 파일에서 특정 닉네임을 삭제하려면 어떻게 해야 합니까?
먼저 파일을 열고 파일에서 모든 줄을 가져옵니다.그런 다음 파일을 쓰기 모드에서 다시 열고 삭제할 줄을 제외한 줄을 다시 씁니다.
with open("yourfile.txt", "r") as f:
lines = f.readlines()
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
당신은 해야 합니다.strip("\n") 바꿈 가장 에 줄 바꿈 문자가 되기 때문에 에서 줄 line하지도 않을 것입니다.
한 번만 열려 있는 상태에서 이 문제를 해결할 수 있습니다.
with open("target.txt", "r+") as f:
d = f.readlines()
f.seek(0)
for i in d:
if i != "line you want to remove...":
f.write(i)
f.truncate()
이 솔루션은 r/w 모드("r+")에서 파일을 열고 탐색을 사용하여 f-point를 재설정한 다음 잘라내기를 수행하여 마지막 쓰기 후 모든 항목을 제거합니다.
목록에 모든 것을 저장하고 파일을 다시 열어 쓰는 것보다 다른 곳에서 파일을 다시 쓰는 것이 가장 좋고 빠른 방법이라고 생각합니다.
with open("yourfile.txt", "r") as file_input:
with open("newfile.txt", "w") as output:
for line in file_input:
if line.strip("\n") != "nickname_to_delete":
output.write(line)
바로 그거야!한 번에 한 번만 같은 일을 할 수 있습니다.그것은 훨씬 더 빠를 것입니다.
이것은 @Lother의 대답에서 나온 "포크"입니다(정답으로 간주되어야 합니다).
다음과 같은 파일의 경우:
$ cat file.txt
1: october rust
2: november rain
3: december snow
다음 코드:
#!/usr/bin/python3.4
with open("file.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "snow" not in line:
f.write(line)
f.truncate()
향상된 기능:
with open는 을무사시것는하의 하는 것입니다.f.close()- 명확한
if/else하기 위해 합니다.
첫 번째 패스에서 행을 읽고 두 번째 패스에서 변경(특정 행 삭제)하는 문제는 파일 크기가 크면 RAM이 부족하다는 것입니다.대신 행을 하나씩 읽고 별도의 파일로 작성하여 불필요한 행을 제거하는 것이 좋습니다.저는 이 접근 방식을 12-50GB 크기의 파일로 실행했지만 RAM 사용량은 거의 일정하게 유지됩니다.CPU 주기만 처리 중인 것으로 표시됩니다.
Linux를 사용하는 경우 다음과 같은 방법을 사용할 수 있습니다.
이름이 지정된 텍스트 파일이 있다고 가정합니다.animal.txt:
$ cat animal.txt
dog
pig
cat
monkey
elephant
첫 번째 줄 삭제:
>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt'])
그리고나서
$ cat animal.txt
pig
cat
monkey
elephant
저는 이 답변에서 설명한 대로 파일 입력 접근법이 마음에 들었습니다: 텍스트 파일에서 줄 삭제(파이톤
예를 들어 빈 줄이 있는 파일이 있는데 빈 줄을 제거하려고 하면 다음과 같이 해결했습니다.
import fileinput
import sys
for line_number, line in enumerate(fileinput.input('file1.txt', inplace=1)):
if len(line) > 1:
sys.stdout.write(line)
참고: 제 경우 빈 줄의 길이는 1입니다.
아마 당신은 이미 정답을 맞았을 것입니다만, 여기 제 것이 있습니다.를 수집하기 위해 하는 대신 (What 필되않데무은수이집기위대사신는용하목해록을하엇를지터터링무▁(대신▁instead▁to(what)▁list는하용▁unf▁a사엇il▁of)readlines()method does), 저는 두 개의 파일을 사용합니다.하나는 기본 데이터를 보류하는 것이고, 다른 하나는 특정 문자열을 삭제할 때 데이터를 필터링하는 것입니다.코드는 다음과 같습니다.
main_file = open('data_base.txt').read() # your main dataBase file
filter_file = open('filter_base.txt', 'w')
filter_file.write(main_file)
filter_file.close()
main_file = open('data_base.txt', 'w')
for line in open('filter_base'):
if 'your data to delete' not in line: # remove a specific string
main_file.write(line) # put all strings back to your db except deleted
else: pass
main_file.close()
이것이 유용하기를 바랍니다! :)
파일을 목록으로 읽어들인 경우 목록 위에 반복하여 삭제할 닉네임을 찾을 수 있습니다.추가 파일을 만들지 않고도 훨씬 효율적으로 작업을 수행할 수 있지만 결과를 원본 파일에 다시 기록해야 합니다.
이를 위한 방법은 다음과 같습니다.
import, os, csv # and other imports you need
nicknames_to_delete = ['Nick', 'Stephen', 'Mark']
내 생각엔nicknames.csv에는 다음과 같은 데이터가 포함됩니다.
Nick
Maria
James
Chris
Mario
Stephen
Isabella
Ahmed
Julia
Mark
...
그런 다음 파일을 목록에 로드합니다.
nicknames = None
with open("nicknames.csv") as sourceFile:
nicknames = sourceFile.read().splitlines()
그런 다음 삭제할 입력과 일치하도록 목록으로 반복합니다.
for nick in nicknames_to_delete:
try:
if nick in nicknames:
nicknames.pop(nicknames.index(nick))
else:
print(nick + " is not found in the file")
except ValueError:
pass
마지막으로 결과를 파일에 다시 기록합니다.
with open("nicknames.csv", "a") as nicknamesFile:
nicknamesFile.seek(0)
nicknamesFile.truncate()
nicknamesWriter = csv.writer(nicknamesFile)
for name in nicknames:
nicknamesWriter.writeRow([str(name)])
nicknamesFile.close()
간단한 해결책은 제안되지 않았습니다.
with open( file_of_nicknames, "r+" ) as f:
lines = f.readlines() # Get a list of all lines
f.seek(0) # Reset the file to the beginning
idx = lines.index("Nickname\n") # Don't forget the '\n'
lines.pop( idx ) # Remove the corresponding index
f.truncate() # Stop processing now
# because len(file_lines) > len( lines )
f.writelines( lines ) # write back
선행 답변에서 영감을 얻음
일반적으로 파일 전체를 다시 작성해야 합니다(최소한 변경 시점부터 끝까지).
어떤 특정한 경우에는 이보다 더 잘 할 수 있습니다.
모든 데이터 요소의 길이가 같고 특정 순서가 없으며 제거할 데이터 요소의 오프셋을 알고 있는 경우 삭제할 데이터 요소 위에 마지막 항목을 복사하고 마지막 항목 앞에 파일을 잘라낼 수 있습니다.
또는 'this is bad data, skip it' 값으로 데이터 청크를 덮어쓰거나 저장된 데이터 요소에 'this item has deleted' 플래그를 유지하여 파일을 수정하지 않고 삭제로 표시할 수 있습니다.
이는 짧은 문서(100KB 미만의 문서)의 경우 오버킬일 수 있습니다.
파일 입력과 'inplace' 방법을 사용하는 이 방법이 좋습니다.
import fileinput
for line in fileinput.input(fname, inplace =1):
line = line.strip()
if not 'UnwantedWord' in line:
print(line)
다른 답변보다 약간 덜 단어적이고 충분히 빠릅니다.
파일 줄을 목록에 저장한 다음 삭제할 줄을 목록에서 제거하고 나머지 줄을 새 파일에 씁니다.
with open("file_name.txt", "r") as f:
lines = f.readlines()
lines.remove("Line you want to delete\n")
with open("new_file.txt", "w") as new_f:
for line in lines:
new_f.write(line)
다음은 파일에서 줄을 제거하는 다른 방법입니다.
src_file = zzzz.txt
f = open(src_file, "r")
contents = f.readlines()
f.close()
contents.pop(idx) # remove the line item from list, by line number, starts from 0
f = open(src_file, "w")
contents = "".join(contents)
f.write(contents)
f.close()
당신은 할 수 .
re
전체 txt 파일을 로드할 수 있다고 가정합니다.그런 다음 원하지 않는 별명 목록을 정의한 다음 빈 문자열 " "로 대체합니다.
# Delete unwanted characters
import re
# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)
파일에서 특정 줄을 제거하여 문장이나 접두사(기호)가 있는 줄을 쉽게 제거할 수 있도록 짧고 간단한 코드를 사용하시겠습니까?
with open("file_name.txt", "r") as f:
lines = f.readlines()
with open("new_file.txt", "w") as new_f:
for line in lines:
if not line.startswith("write any sentence or symbol to remove line"):
new_f.write(line)
파일의 특정 행을 해당 행 번호로 삭제하는 방법
변수 파일 이름과 line_to_delete를 파일 이름과 삭제할 줄 번호로 바꿉니다.
filename = 'foo.txt'
line_to_delete = 3
initial_line = 1
file_lines = {}
with open(filename) as f:
content = f.readlines()
for line in content:
file_lines[initial_line] = line.strip()
initial_line += 1
f = open(filename, "w")
for line_number, line_content in file_lines.items():
if line_number != line_to_delete:
f.write('{}\n'.format(line_content))
f.close()
print('Deleted line: {}'.format(line_to_delete))
출력 예:
Deleted line: 3
파일의 내용을 새 줄로 나누어 튜플로 만듭니다.그런 다음 튜플의 줄 번호에 액세스하고 결과 튜플에 가입한 다음 파일에 덮어씁니다.
언급URL : https://stackoverflow.com/questions/4710067/how-to-delete-a-specific-line-in-a-text-file-using-python
'programing' 카테고리의 다른 글
| Android Pull-to-Refresh를 구현하는 방법 (0) | 2023.07.08 |
|---|---|
| Git: Windows용 GitHub 클라이언트로 Git in PATH 설치 (0) | 2023.07.08 |
| 기존 repo의 분기에서 새 GitHub repo를 만들려면 어떻게 해야 합니까? (0) | 2023.07.08 |
| ObjectId'를 사용하여 MongoDB 쿼리 (0) | 2023.07.08 |
| Angular FormArray 디스플레이 유효성 검사 오류 (0) | 2023.07.08 |