반응형
파일 내용 내에서 문자열 바꾸기
Stud.txt 파일을 열고 "A"를 "Orange"로 바꾸려면 어떻게해야합니까?
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
같은 파일의 문자열을 바꾸고 싶다면 아마도 그 내용을 로컬 변수로 읽어 들인 다음 닫고 쓰기 위해 다시 열어야 할 것입니다 :
이 예제에서는 블록이 종료 된 후 파일을 닫는 with 문 을 사용 하고with
있습니다. 일반적으로 마지막 명령이 실행을 완료하거나 예외로 인해 파일이 닫힙니다 .
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
s = f.read()
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
파일 이름이 다르면 단일 with
명령문으로 더 우아하게이 작업을 수행 할 수 있다는 점을 언급 할 가치가 있습니다 .
#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
같은 것
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
with open('Stud.txt','r') as f:
newlines = []
for line in f.readlines():
newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
for line in newlines:
f.write(line)
Linux를 사용 중이고 단어 dog
를 cat
다음 과 같이 바꾸려면 다음을 수행하십시오.
text.txt :
Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Linux 명령 :
sed -i 's/dog/cat/g' test.txt
산출:
Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...
import re
input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
input.write(each)
참고URL : https://stackoverflow.com/questions/4128144/replace-string-within-file-contents
반응형
'developer tip' 카테고리의 다른 글
스낵바의 배경색을 변경하는 방법은 무엇입니까? (0) | 2020.09.15 |
---|---|
.dll과 .exe의 차이점은 무엇입니까? (0) | 2020.09.15 |
AJAX로 부트 스트랩 팝 오버 콘텐츠를로드합니다. (0) | 2020.09.15 |
Gulp 오류 : 감시 작업은 함수 여야합니다. (0) | 2020.09.15 |
UILabel 글꼴 크기? (0) | 2020.09.15 |