다른 스크립트를 사용하여 코드에서 후행 공백을 제거하는 방법은 무엇입니까?
다음과 같은 것 :
import fileinput
for lines in fileinput.FileInput("test.txt", inplace=1):
lines = lines.strip()
if lines == '': continue
print lines
그러나 stdout에는 아무것도 인쇄되지 않습니다.
다음과 같은 문자열을 가정합니다 foo
.
foo.lstrip() # to remove leading white space
foo.rstrip() # to remove trailing whitespace
foo.strip() # to remove both lead and trailing whitespace
fileinput
여러 입력 스트림을위한 것 같습니다. 이것이 내가 할 일입니다.
with open("test.txt") as file:
for line in file:
line = line.rstrip()
if line:
print(line)
키워드 인수 가 제공 되면 입력 파일로 리디렉션 print
되기 때문에 명령문의 출력이 표시되지 않습니다 . 이로 인해 입력 파일이 효과적으로 다시 작성되고 나중에 살펴보면 그 안에있는 줄에 실제로 후행 또는 선행 공백이 없습니다 ( 문이 다시 추가 되는 각 줄의 끝에있는 줄 바꿈 제외 ).FileInput
stdout
inplace=1
print
후행 공백 만 제거하려면 rstrip()
대신을 사용해야 합니다 strip()
. 또한 참고 if lines == '': continue
인 원인 빈 줄이 완전히 (여부에 관계없이의 제거 할 strip
또는 rstrip
사용됩니다).
입력 파일을 다시 작성하려는 의도가 아니라면 for line in open(filename):
. 그렇지 않으면 sys.stderr
다음과 같은 것을 사용하여 출력을 동시에 에코하여 파일에 기록되는 내용을 볼 수 있습니다 .
import fileinput
import sys
for line in (line.rstrip() for line in
fileinput.FileInput("test.txt", inplace=1)):
if line:
print line
print >>sys.stderr, line
PEP8을 정리하려는 경우 전체 프로젝트의 후행 공백을 제거합니다.
import os
PATH = '/path/to/your/project'
for path, dirs, files in os.walk(PATH):
for f in files:
file_name, file_extension = os.path.splitext(f)
if file_extension == '.py':
path_name = os.path.join(path, f)
with open(path_name, 'r') as fh:
new = [line.rstrip() for line in fh]
with open(path_name, 'w') as fh:
[fh.write('%s\n' % line) for line in new]
이 물건의 일종 sed
이다 정말 잘 : $ sed 's/[ \t]*$//'
. \t
이 작업을 수행하는 대신 TAB 문자를 문자 그대로 입력해야 할 수도 있습니다.
fileinput.FileInput은 생성기입니다. 따라서 한 번만 반복 할 수 있으며 모든 항목이 소비되고 다음 메서드를 호출 하면 StopIteration이 발생 합니다. 행을 두 번 이상 반복하려면 목록에 넣을 수 있습니다.
list(fileinput.FileInput('test.txt'))
그런 다음 rstrip 을 호출하십시오 .
다른 이름으로 저장 fix_whitespace.py
:
#!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""
import os
import sys
def main():
""" Parse arguments, then fix whitespace in the given file """
if len(sys.argv) == 2:
fname = sys.argv[1]
if not os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
sys.exit(1)
fix_whitespace(fname)
def fix_whitespace(fname):
""" Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lines):
new_line = line.rstrip()
if len(line) != len(new_line):
lines[k] = new_line
fixed += 1
with open(fname, "wb") as fo:
fo.write("\n".join(lines))
if fixed or contents != original_contents:
print("************* %s" % os.path.basename(fname))
if fixed:
slines = "lines" if fixed > 1 else "line"
print("Fixed trailing whitespace on %d %s" \
% (fixed, slines))
if contents != original_contents:
print("Fixed line endings to Unix (\\n)")
if __name__ == "__main__":
main()
여러 python
줄 프로그램을 작성할 필요가 없기 때문에이 작업 에 사용할 것을 제안하는 여러 답변을 보는 것은 약간 놀랍습니다 .
sed
, awk
또는 같은 표준 Unix 도구 perl
는 명령 줄에서 직접 쉽게 수행 할 수 있습니다.
예를 들어 어디서든 perl
(일반적으로 Windows, Mac, Linux) OP에서 요청한 내용을 다음과 같이 달성해야합니다.
perl -i -pe 's/[ \t]+$//;' files...
Explanation of the arguments to perl
:
-i # run the edit "in place" (modify the original file)
-p # implies a loop with a final print over every input line
-e # next arg is the perl expression to apply (to every line)
s/[ \t]$//
is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.
Advantages:
- One liner, no programming needed
- Works on multiple (any number) of files
- Works correctly on standard-input (no file arguments given)
More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO
with BAR
, you may always use this generic template:
perl -i -pe 's/FOO/BAR/' files...
'Nice programing' 카테고리의 다른 글
rake db : schema : dump는 마이그레이션 또는 데이터베이스 자체에서 schema.rb를 다시 생성합니까? (0) | 2020.12.12 |
---|---|
Django에서 정적 파일과 미디어 파일의 차이점은 무엇입니까? (0) | 2020.12.12 |
git add -A는 디렉토리의 모든 수정 된 파일을 추가하지 않습니다. (0) | 2020.12.12 |
NumPy가 뷰 또는 복사본을 생성하는지 어떻게 알 수 있습니까? (0) | 2020.12.12 |
분수를 유지하면서 문자열을 소수로 변환 (0) | 2020.12.11 |