Python 파일 검색 및 다른 텍스트 길이로 바꾸기
Python 3를 사용하여 파일 내에서 검색 및 바꾸기를 수행하려고 시도하는 동안 일부 사용자 대체 텍스트가 원본 텍스트보다 짧거나 길면 문제가 발생합니다. 이로 인해 의도하지 않은 문자가 파일에 추가될 수 있습니다.
제공된 코드를 고려하십시오.
# Get user input for search and replacement text textToSearch, textToReplace, fileToSearch = input("Text to search for: "), input("Text to replace it with: "), input("File to perform Search-Replace on: ") # Open the file and loop through each line with open(fileToSearch, 'r+') as tempFile: for line in fileinput.input(fileToSearch): # Perform replacement only when a match is found if textToSearch in line: line = line.replace(textToSearch, textToReplace) # Write the modified line back to the file tempFile.write(line)
그러나 이 접근 방식은 긴 텍스트를 더 짧은 텍스트로 바꾸는 경우 실패합니다. 원본 텍스트가 남습니다 뒤에.
해결책:
이 문제를 해결하려면 전체 파일을 메모리로 읽고 검색 및 바꾸기 작업을 수행한 다음 수정된 파일을 쓰는 것이 좋습니다. 별도의 단계로 콘텐츠를 파일로 되돌립니다.
# Read the file into memory with open('file.txt', 'r') as file: filedata = file.read() # Perform the replacement filedata = filedata.replace('abcd', 'ram') # Write the modified content back to the file with open('file.txt', 'w') as file: file.write(filedata)
이 방법을 사용하면 의도하지 않은 내용을 추가하지 않고 파일이 제자리에서 수정됩니다. 문자입니다.
위 내용은 Python의 검색 및 바꾸기는 파일 편집 시 가변 텍스트 길이를 어떻게 처리할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

pythonlistsareimplementedesdynamicarrays, notlinkedlists.1) thearestoredIntIguousUousUousUousUousUousUousUousUousUousInSeripendExeDaccess, LeadingSpyTHOCESS, ImpactingEperformance

PythonoffersfourmainmethodstoremoveElementsfromalist : 1) 제거 (값) 제거 (값) removesthefirstoccurrencefavalue, 2) pop (index) 제거 elementatAspecifiedIndex, 3) delstatemeveselementsByindexorSlice, 4) RemovesAllestemsfromTheChmetho

Toresolvea "permissionDenied"오류가 발생할 때 오류가 발생합니다.

arraysarecrucialinpythonimageProcessingAstheyenableantureficient -manipulationand analysysofimagedata.1) ImagesAreconTortonumpyArrays, withGrayScaleImages2DarraysAndColorImagesS3darrays.2) arraysallowforvectorizedoperations, inablingastAdmentments bri

ArraysareSareSareStificerTanlistSforoperationsbenefitingfrom DirectMemoryAccessandfixed-sizestructures.1) AccessingElements : ArraysprovideConstant-timeaccessduetocontiguousUousUousSougues.2) 반복 : ArraysleAgeCachelocalityFasterItertion.3) Mem

ArraysareBetterForElement-WiseOperationsDuetOfasterAcccessandoptimizedimmentations.1) ArraysHaveCecontIguousMemoryFordirectAccess, 향상

Numpy에서 전체 배열의 수학적 작업은 벡터화 된 작업을 통해 효율적으로 구현 될 수 있습니다. 1) 추가 (ARR 2)와 같은 간단한 연산자를 사용하여 배열에서 작업을 수행하십시오. 2) Numpy는 기본 C 언어 라이브러리를 사용하여 컴퓨팅 속도를 향상시킵니다. 3) 곱셈, 분할 및 지수와 같은 복잡한 작업을 수행 할 수 있습니다. 4) 배열 모양이 호환되도록 방송 작업에주의를 기울이십시오. 5) NP.Sum ()과 같은 Numpy 함수를 사용하면 성능을 크게 향상시킬 수 있습니다.

Python에는 요소를 목록에 삽입하는 두 가지 주요 방법이 있습니다. 1) 삽입 (인덱스, 값) 메소드를 사용하여 지정된 인덱스에 요소를 삽입 할 수 있지만 큰 목록의 시작 부분에서 삽입하는 것은 비효율적입니다. 2) Append (value) 메소드를 사용하여 목록 끝에 요소를 추가하여 매우 효율적입니다. 대형 목록의 경우 Append ()를 사용하거나 Deque 또는 Numpy Array를 사용하여 성능을 최적화하는 것이 좋습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

드림위버 CS6
시각적 웹 개발 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기