이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

탭을 공백 문자로 바꾸기

A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.

A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.

2014/02/26 22:53

pahkey

반대로 문제를 공백4개를 탭으로 바꾸라고 했으면 좀더 어려운 문제가 될뻔, 빌트인 함수라고 해도 replace 로 구현하면 알고리즘 문제가 되지 않죠. 실무에서 라면 몰라도, replace를 사용하지 않고 구현하라는 부분이 추가되면 좋겠네요. - 이 종성, 2016/09/15 13:57
+4 이 문제가 쉬운문제이긴 하나 많은 분들이 실수하고 계신것이 있네요. 분명 탭으로들여 쓰기가된 부분만 공백으로 바꾸어야 하는데 소스코드 중간에 들어가있는 탭까지 공백으로 바꾸는 문제풀이들이 많군요 - 윤태호, 2016/11/02 01:55
문제 풀이에 그런 말이 없어서 당연한 것 아닐까요. 게다가 문서 중간에 탭을 쓰는 경우도 거의 없고. - Flair Sizz, 2016/11/06 15:34
+1 문제의 첫 두줄은 예를 들어 상황을 설명한 것이고. 문제는 마지막 줄에 있네요. 소스코드내에 사용된 탭 문자를 공백으로 바꾸라고 되어 있습니다. 들여쓰기 탭문자만 공백으로 바꾸라는 말은 없습니다. - Scott.Jun, 2017/02/19 00:03

512개의 풀이가 있습니다.

대화형으로 사용할수있게 작성해보았습니다.

해당파일들 위치에 백업파일 생성후 기존파일에 탭을 스페이스로 변환 합니다.

# -*- coding:utf-8 -*-
import os
import re
filepath    = input('파일이 위치한 경로를 입력하세요:')
ext         = input('확장자를 입력하세요: '            )


'''파일경로와 확장자를 파라메터로 받아서 하위디렉토리 모두 탐색해서 조건에
맞는 파일전체경로를 list 에 담아 리턴한다.'''
def getFileList(filepath,ext):
    _filelist = []
    for cur, _dirs, files in os.walk(filepath):
        for filenm in files:
            if (filenm.lower()).endswith(ext.lower()):
                _filelist.append(cur+"\\"+filenm)

    return _filelist


for _path in getFileList(filepath,ext):
    print(_path)
    os.system ("copy %s %s" % (_path, _path+".bak")) #백업파일 생성

    with open( _path+".bak",'r') as f:
        srcContent = f.read()
        with open(_path,"w") as writelist:
            writelist.write(srcContent.replace("\t","    "))

2014/03/04 13:34

무명소졸

+1 와, 실용적인 프로그램을 만드셨네요 ^^ - pahkey, 2014/03/04 21:52
멋지네요 ^^b - Jung Daehyun, 2017/08/01 00:18

파이썬 3.4 입니다.

filename=input("Enter your file name : ")
tempfile=open(filename)
tempfile=tempfile.read()
temp_str=tempfile.replace("\t","    ")
tempfile=open(filename,'w')
tempfile.write(temp_str)
tempfile.close()

2014/09/22 21:20

돌구늬ㅋ~썬

펄입니다

for(<STDIN>){s/^\t/    /g;print}

리눅스셸에서 다음과 같이 사용 가능

$perl -e 'for(<STDIN>){s/^\t/    /g;print}' <INPUTFILE >OUTPUTFILE

2014/12/20 01:17

이병곤

coding by python beginner

import sys, os
f = open( sys.argv[1], 'r' )
t0 = f.read()
f.close()

f = open( sys.argv[1], 'w' )
f.write( t0.replace( '\t', ' ' * 4 ) )
f.close()

os.system( 'cat ' + sys.argv[1] )

2015/01/23 10:08

vegan

static void Main(string[] args)
        {
            string Text = File.ReadAllText(@"E:\TebTest.txt");
            Text = Text.Replace('\t', ' ');
            Text = Text.Replace(" ", "    ");

            Console.WriteLine(Text);
        }

2015/06/14 17:18

허 빈

#include <stdio.h>

int main(void)

{
    char str[] = { "Test\tS\ttring" };

    int i = 0;

    for (i = 0; i < sizeof(str); i++)
    {
        if (str[i] == '\t')
        {
            str[i] = ' ';
        }
    }

    printf("%s\n", str);

    return 0;
}

파일입출력은 공부하지 않아서 example string에 포함된 Tab을 Space로 바꾸는 코드를 작성하였습니다.

2015/11/12 19:33

Newbi_Hj

String tapToSpace(String text) {
        text.replaceAll("\t", " ");
        return text;
    }

java

2016/03/15 01:14

mozzi

#import <Foundation/Foundation.h>

BOOL(^ExistFile)(NSString *)=
^(NSString *path){
    NSFileManager * tmpManager = [ NSFileManager defaultManager ];
    if( [ tmpManager fileExistsAtPath:path ] )
        return YES;

    return NO;
}; // 파일 존재여부 확인

NSData *(^TabToSpace)(NSData *)=
^(NSData *current){ // 입력받은 문자, 탭, 공백을 NSString으로 변환해서 비교/작업
    NSString * buf = [ NSString stringWithUTF8String: [ current bytes ] ];
    NSString * tab = [ NSString stringWithFormat:@"\t" ];
    NSString * change = [ NSString stringWithFormat:@"    " ];

    if( tab == buf )
        current = [ change dataUsingEncoding:NSUTF8StringEncoding ];
    return current;
}; // current가 탭인지 확인해서 맞다면 공백 반환, 아니면 그대로 반환

int main(int argc, const char * argv[])
{
    @autoreleasepool {

        NSFileManager * myManager = [ NSFileManager defaultManager ]; // 파일 제어 관련

        NSString * path =
        [ NSString
            stringWithFormat:
        @"/Users/outlt/Desktop/outlt/Stamp/TabToSpace/TabToSpace/" ]; // 파일 다룰 경로

        NSString * file1 = [ NSString stringWithString:
                            [ path stringByAppendingString:@"tab.txt" ] ]; // 파일이름 ( 원본 )
        NSString * file2 = [ NSString stringWithString:
                            [ path stringByAppendingString:@"result.txt" ] ]; // 파일이름 ( 탭제거후 )

        [ myManager createFileAtPath:file2 contents:nil attributes:nil];
        // 새로운 파일 생성

        if( !( ExistFile(file2) && ExistFile(file1) ) ){
            NSLog(@" 파일이 없음"); return 1;
        } // 파일 2개 존재 확인

        NSFileHandle * file =
        [ NSFileHandle fileHandleForReadingAtPath: file1 ]; // 원본파일을 읽기로 열기

        NSFileHandle * result =
        [ NSFileHandle fileHandleForWritingAtPath:file2 ];  // 만든파일을 쓰기로 열기

        unsigned long long mySeek = [ file seekToEndOfFile ] ; // 파일 내용의 용량
        [ file seekToFileOffset:0 ]; // 파일포인터를 맨뒤로 보내서 파일용량을 확인했으므로 다시 처음으로


        while ( [ file offsetInFile ] < mySeek ) // 파일의 마지막까지 1바이트씩
        {
            NSData * data = [ file readDataOfLength:1]; // 1바이트 읽기
            [ result writeData: TabToSpace(data) ]; // 쓰기
        }
    }
    return 0;
}

2014/08/31 22:25

식빵

// C# 입니다.
using System;

class Program
{
    static string input = "\ttab\t\ttabtab";

    static void Main()
    {
        string output = input.Replace("\t", "    ");
        Console.WriteLine(input);
        Console.WriteLine(output);
    }
}

2014/09/29 16:23

보헤미안

package change_tab_to_blank;

import java.io.*;

public class changetab {
    public static void main(String[] args)
    {
        try{
            //파일로부터 입력받음
            File input_file = new File("input.txt");
            FileReader fileReader = new FileReader(input_file);
            BufferedReader reader = new BufferedReader(fileReader);     
            //출력 대상 파일 설정
            FileWriter fileWriter = new FileWriter("output.txt");
            BufferedWriter writer = new BufferedWriter(fileWriter);

            int input_ascii;

            while( ( input_ascii = reader.read() ) != -1 ){
                //문자하나하나는 아스키로 받아와서 char형으로 변환하여 사용
                char input_char = (char)input_ascii;

                if( input_char == 9 ){
                    //tab의 아스키코드는 9, 공백의 아스키코드는 32
                    input_char = 32;
                    //탭만나면 공백 4번
                    for( int i=1; i<=4; i++){
                        writer.write( input_char );
                        //System.out.print(input_char);
                    }
                }
                else{   //탭 아닌 다른 문자들은 그냥 그대로 출력
                    writer.write( input_char );
                    //System.out.print(input_char);
                }

            }
            writer.close(); //안닫아주면 안됨
            reader.close();

        }
        catch(Exception ex){

        }
    }
}

2015/02/19 02:59

zerofury

def tab_to_space(text): return text.replace("\t", " " * 4)

2018/08/06 14:47

로봇

f = open("./aaa.txt.", 'r') # 소스코드가 aaa 파일에 있다고 가정
lines = f.readlines()
f.close()
f = open("./bbb.txt", 'w') # 수정할 코드를 bbb 파일에 저장
for line in lines:
    f.write(line.replace("\t", "    "))
f.close()

2019/02/14 11:12

김상민

filename = input('write filname : ')

with open(filename, 'r') as f:
    f = f.read()

a = f.replace("\t","    ")

with open(filename,'w') as f:
    f.write(a)

2022/10/17 14:49

jh

Clojure 코드입니다.

#(spit % (clojure.string/replace (slurp %) "\t" "    "))

2014/02/27 00:10

박연오

slurp은 파일 입력 / spit은 파일 출력 함수입니다. - 박연오, 2014/02/27 00:11
정말 깔끔합니다. 입출력 함수명이 참 특이하네요 ^^ - pahkey, 2014/02/27 00:32
한국어로 번역하면 입력: '후루룹', 출력: '퉤' 죠 ㅋㅋ - 박연오, 2014/02/27 00:44

Ruby.

def tab_to_four_space(text); text.gsub(/^(\t+)/){"    " * $1.size}; end

2014/02/28 04:03

nacyot

Python

def tab_to_spaces(text):
    return text.replace("\t","    ")

2014/02/28 20:03

정훈

clojure

(defn tab->space [text]
  (-> text
      (clojure.string/replace #"\t" "    ")))

2014/03/23 06:03

김 은평

#tts.py

import sys

def usage():
    print("Usage: python %s filename" % sys.argv[0])

try: f = open(sys.argv[1])
except: usage(); sys.exit(2)

msg = f.read()
msg = msg.replace('\t'," "*4)

f.close()

f = open(sys.argv[1], 'w')
f.write(msg)
f.close()

2014/04/14 00:25

서 동현

파이썬 입니다.

# cod_tabto4.py

import re
import sys

def tab_to_space(file_name):
        source_cod = file_name.read()
        file_name.close()
        patturn = re.compile(r'\t')
        changed = patturn.sub("    ", source_cod)
        file_name = open(sys.argv[1],'w')
        file_name.write(changed)
        file_name.close()

try:
        file_name = open(sys.argv[1])
        tab_to_space(file_name)
except:
        print("Usage: python %s filename" % sys.argv[0])
        sys.exit(2)

2014/05/04 10:29

재민스

Python 3.4

def tab_trans(text):
    return text.replace('\t', '    ')

2014/05/14 04:39

TEMS

import re
import sys

def usage():
    print("Usage: python %s filename [no. of space]" % sys.argv[0])

try: 
    f = open(sys.argv[1])
except:
    usage(); sys.exit(2)

msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*int(sys.argv[2]), msg)

f = open(sys.argv[1], 'w')
f.write(changed)
f.close()

2014/05/16 14:54

superarchi

python 입니다.

import unittest

def method1(str):
    return str.replace('\t', '    ')


class TestTab2Space(unittest.TestCase):
    def test_method1(self):
        str = "Hello\tMy Friend."
        self.assertEqual(method1(str), "Hello    My Friend.")

if __name__ == "__main__":
    unittest.main()

2014/07/19 17:32

이 정구

public class ChangeSpaceFromTab {

    //소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램
    public static void main(String[] args) {
        String text = "Today is a gift\tTomorrow is a mistery\tby Kung fu panda.";
        String replaceSpaceFromTab = replaceSpaceFromTab(text);
        System.out.println(replaceSpaceFromTab);
    }

    private static String replaceSpaceFromTab(String text) {
        String replaceAll = text.replaceAll("\t", " ");
        return replaceAll;
    }
}

2014/07/27 17:52

전 수현

def tab_to_space(text):
    return text.replace("\t", " " * 4)

2014/09/03 02:23

이 한종

자바 내장함수 replaceAll 사용했습니다.
public class T {
    public static void main(String[] args) {
        String str="aaa\taaa\taaa";
        System.out.println(str);


        str=str.replaceAll("\t","    ");
        System.out.println(str);


    }

}

2014/09/23 18:41

임시

string = "haha  my  name    is  sauron\n"

def changeTabToSpace():
    newString = ""
    for char in string:
        if char == '\t':
            char = '    '
        newString+=char
    return newString

newString = changeTabToSpace()

print string,"\n",newString

replace안쓰고 파일 입출력 제외한 파이썬코드

2014/10/25 18:35

원 동건

//bin 경로에 tab.txt 파일 작성 후 테스트. 한글 가능


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class TabToSpaceMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        tabChange(TabToSpaceMain.class.getResource("").getPath(), "tab.txt");
    }

    public static void tabChange(String filePath, String filename) {
        String s = "";
        String sNew = "";
        BufferedReader bf = null;
        BufferedWriter bw = null;

        try {
            bf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + filename),"euc-kr"));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath + "new_" + filename)));

            while((s = bf.readLine()) != null) {
                sNew = s.replaceAll("\t", "    ");
                bw.write(sNew);
                bw.newLine();
            }

            bf.close();
            bw.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

2014/11/14 22:19

김 연태

    text = "abcdefghijk    lmnopqrstuvwxyz"
    text.replace("\t", "    ")
    print text

python2.7

2014/11/25 10:34

아으다롱디리

파이썬 2.7입니다. 소스코드에 한글이 없길 기도하며....

def convertTap(str,rep=' ',count=4):
    return str.replace('\t',rep*count)

def process(filepath):
    with open(filepath, 'rw') as f:
        transformed  = convertTap(f.read())
        f.write(transformed)

import sys

def main():
    if len(sys.argv) > 1:
        for filepath in sys.argv[1:]:
            process(filepath)

if __name__ == "__main__":
    main()

2014/12/11 14:28

룰루랄라

Perl

while(<>){s/^((\t)\2+)/' ' x 4*(length $1)/eg;print}

2015/01/02 21:12

*IDLE*

파이썬입니다.

str = """ ... """
str = str.replace('\t', '    ')
print(str)

2015/01/13 15:43

Kim SangWon

파이썬 3.4 입니다.

#tab_to_4_space.py
#vim을 활용한 python프로그램 
#코딩도장 lv.1 탭을 공백문자 4개로 바꾸기

def conv_tab(text):
    result = text.replace("\t","    ")
    return result

text = input("변환할 문자열")

print(conv_tab(text))

2015/01/18 19:43

김 준수

def tabToSpace(text:String) = text.map{case '\t' => "    "; case c => c+""}.reduce(_+_)

2015/01/23 01:40

이 호연

먼저 파일 이름을 입력받습니다. 그리고 새로 작성할 파일이름을 만듭니다.

file_name=raw_input("file_inputname:")
new_file_name=file_name +"_new"

파일을 열고

f=open(file_name,'r')
file=f.readlines()

new_f=open(new_file_name,'w')


탭을 공백으로 치환합니다. 그리고 파일을 닫습니다.

for i in file:
    test=i.replace("\t","    ")
    new_f.write(test)


f.close()
new_f.close()

2015/01/27 17:34

이 승훈

초보라,, 동작은 됩니다.

file = input("type the target file: ")
f = open(file)
msg = f.read()
f.close()

f = open(file,'w')
f.write(msg.replace("\t", "    "))
f.close()

2015/01/29 14:37

최 진열

자바 입니다. replaceAll을 굳이 쓰지 않고 replace를 써도 전체 tab이 바뀝니다. 그리고, 눈으로 확인하는 것 보다 Test코드 통과 여부를 보면 좋을 것 같아서 테스트코드도 함께 넣습니다.


public class Tab2Space {
    /**
     * Tab -> Space(4blank) 
     * @param originStr
     * @return
     */
    public String convertTab2Space(String originStr){
        String returnString = null;
        if (originStr != null) {
            returnString = originStr.replace("\t", "    ");
        }
        return returnString; 
    }
}

아래는 테스트 코드 입니다.


import static org.junit.Assert.*;

import org.junit.Test;

public class Tab2SpaceTest {

    @Test
    public void testConvertTab2Space() {
        String originString = "abc\tdef";
        String expectedString = "abc    def";
        String actualString = new Tab2Space().convertTab2Space(originString);
        assertEquals(expectedString, actualString);
    }

    @Test
    public void testConvertTwoTab2Space() {
        String originString = "abc\t\tdef";
        String expectedString = "abc        def";
        String actualString = new Tab2Space().convertTab2Space(originString);
        assertEquals(expectedString, actualString);
    }

    @Test
    public void testEmptyConvert(){
        String originString = null;
        String expectedString = null;
        String actualString = new Tab2Space().convertTab2Space(originString);
        assertEquals(expectedString, actualString);
    }
}

2015/02/02 21:38

임 성현

Python

import sys

# 시스템 매개변수로 파일명 받아서 처리
args = sys.argv[1:]
filename = args[0]

try:
    with open(filename, 'rb') as tab_file:
        source = tab_file.readlines()           # 파일내 글 모두 읽는다.
        target = "".join(source)                # 읽어온 데이터는 list 타입이라 스트링으로 변환
        target = target.replace("\t", "    ")       # 탭을 공백으로 변환

        with open('space4.txt','wb') as space_file:
            space_file.write(target)            # 새로운 파일에 저장
except IOError as err:
    print('File error: ' + str(err))

2015/02/03 12:37

Kang MinSu

def tabToSpace(input: String): String = {
    val pattern = "^(\t+)".r

    pattern.replaceAllIn(input, { m =>
        m.subgroups.map(_.replace("\t", "    ")).mkString("")
    })
}


println(tabToSpace("\ttest"))
println(tabToSpace("\t\ttest"))


println(
    io.Source.fromFile("TabToSpace.scala").getLines.map(tabToSpace).mkString("\n")
)

2015/02/05 10:45

killbirds

%s;\t;    ;g

vim 입니다

2015/02/12 01:09

Yoo KyungSik

import sys
import re

def tabto4(filename):
    f = open(filename)
    txt = f.read()
    p = re.compile(r'\t')
    txt = p.sub(" "*4, txt)
    f.close()

    f = open(filename, "w")
    f.write(txt)
    f.close()


if __name__ == "__main__":
    tabto4(sys.argv[1])

2015/03/17 18:17

임 진승

#tab to 4space

import re
import sys

def tabToSpace():
    print "file name" % sys.argv[0]

try : f = open(sys.argv[1])
except : tabToSpace(); sys.exit(2)

code = f.read()
f.close()
changedCode = code.replace("\t", " "*4)
f = open(sys.argv[1] , 'w')
f.write(changedCode)
f.close()

2015/03/20 23:00

seungdols

using python

f = open("tap.txt","r").read()

f = f.replace("\t","    ")

g = open("tap.txt","w")

g.write(f)
g.close()

2015/03/28 20:24

freeefly

PHP

<?php
$get = fgets(STDIN); // 내용을 불러온다.
echo preg_replace("/\t/", "    ", $get); // $get에서 'Tab'을 '    '로 변환시킨다
?>

간단하게 되네요.

2015/04/20 22:43

장 효찬

Javascript

"문자열".replace(/\t/g, "    ");

2015/05/06 14:49

JakartaKim

김명훈님 방법보고 따라서 만들어봤어요 ! os.walk !강력하면서 아직 좀 어렵네요 ㅠㅠ

import os
import shutil
import re


filepath=raw_input("directory")
ext=raw_input("ext")

"""원하는 디렉토리 안의 확장자 파일을 리스트로 받는다"""
def getFileList(filepath,ext):
    _filepath=[]
    for root,dirpath,filename in os.walk(filepath):
        for file1 in filename:
            if os.path.splitext(file1)[-1]==ext:
                _filepath.append(root+"/"+file1)
    return _filepath


""" tab을     로 바꿔주는 함수"""
def tab_to_space(text):
    text2=text.replace("\t","    ")
    return text2

Filelist=getFileList(filepath,ext)

for files in Filelist:
    shutil.copyfile(files,files+".dat")
    f=open(files,"w")
    g=open(files+".dat","r")
    f.write(tab_to_space(g.read()))
    f.close()

2015/05/06 18:11

심재용

풀이 비교해보면 for문 뒤에나, 필요없는 함수 설정등을 줄여가면서 소스를 읽기쉽게 해놓으셨군요! - 심재용, 2015/05/06 18:12
My.Computer.FileSystem.WriteAllText("Path", My.Computer.FileSystem.ReadAllText("Path").Replace(Chr(9), Space(4)), False)

읽어온뒤 바로 수정후 저장을합니다.

2015/06/13 01:15

Steal

<?php

$in = "     tood    net ";
$out = preg_replace("\t","    ",$in);
echo $out;

?>

php로도 간단히 가능하네요!

2015/06/13 01:24

hanjonghoon

content.replace("\t","    ")

2015/06/15 01:34

손 진혁

파일을 로드해야해요. - 문성훈, 2015/06/15 01:36
            string input = "AB  CD  DEF";
            input = input.Replace("\t", "    );

            Console.WriteLine(input);

2015/06/27 07:07

Raye

(자바)

일단 스캐너로 문자열을 입력받고 이것을 문자배열로 바꾼후 반복문을통해 문자중 일반 문자는 그대로 출력하고 탭키를 만날시 이것을 스페이스바4개로 출력하게 만들었습니다 처음엔 배열값자체에 넣은후 한번에 출력하려고 하였으나 String과 char형의 타입이 맞지않아 이런식으로 짜보았습니다.

package dojavn;
import java.util.Scanner;
public class dsa {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);

        String ta=sc.nextLine();
        char [] s=ta.toCharArray();

        for(int i=0;i<s.length;i++)
        {

            if(s[i]=='\u0009'){
                System.out.print("    ");


            }
            else{

            System.out.print(s[i]);
            }
        }

    }

}

2015/07/03 05:09

사석훈

import java.io.*;

public class TabTo4Spaces {
    String orgDir = "C:/docs";
    String descDir = "C:/docs2";

    public static void main(String[] args) throws Exception {
        TabTo4Spaces tt4 = new TabTo4Spaces();

        tt4.convert(new File(tt4.orgDir));
    }

    public void convert(File file) throws IOException{

        if (file.isDirectory()) {
            String path = file.getAbsolutePath().replace("\\", "/");
            String newPath = path.replace(orgDir.replace("\\", "/"), descDir);

            File newDir = new File(newPath);
            newDir.mkdir();

            if (!newDir.exists()) {
                newDir.mkdir();
            }

            File[] files = file.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return  pathname.isDirectory() || pathname.getName().contains("txt");
                }
            });

            for (File f : files) {
                convert(f);
            }
        } else {
            tabTo4Spaces(file);
        }
    }

    public void tabTo4Spaces(File org) throws IOException {
        String orgParentPath = org.getParent().replace("\\", "/");
        String newPath = orgParentPath.replace(orgDir.replace("\\", "/"), descDir);

        BufferedReader br = new BufferedReader(new FileReader(org));
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File(newPath+"/"+org.getName())));

        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line.replaceAll("\\t", "    "));
            bw.newLine();
        }

        bw.close();
        br.close();
    }
}

지정된 root디렉토리부터 하위 디렉토리를 재귀함수로 돌려 txt 파일만 변환했습니다. 코드가 지저분... 다시 정리 해야겠네요;

2015/08/04 01:00

원동빈

#include "stdafx.h"
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream fin;
    ofstream fout;
    fin.open("Original.txt");
    fout.open("Fixed.txt");

    vector<string> arString;

    while(!fin.eof())
    {
        string strTemp;
        getline(fin, strTemp);
        arString.push_back(strTemp);        
    }

    for (int i = 0; i < (int)arString.size(); ++i)
    {
        string strTemp = arString[i];

        if (strTemp[0] == '\t')
        {
            strTemp.erase(0, sizeof(char));
            strTemp.insert(0, "    ");
        }

        fout << strTemp << endl;
    }
    int a= 0;

    fin.close();
    fout.close();

    return 0;
}

2015/08/10 20:32

박 해수

<?php
// \t -> &nbsp * 4;

$temp_str = "내          용  **   내용";
$temp_str = str_replace("\t","&nbsp&nbsp&nbsp&nbsp",$temp_str);

echo $temp_str;
?>

2015/08/28 16:42

mung mangmang

replace 몰랐음. 콘솔로 확인 후 파일 저장


def swap():
    f = open('test.txt','r')
    print 'before'
    for data in f.readlines():
        print data,
    print ('')

    # Pointer rewind
    f.seek(0)

    new_f = open('changed.txt','w')
    print 'after'
    for data in f.readlines():
        if data.startswith('\t'):
            chs = data[1:]
            space = '    ' + chs
            print space,
        else:
            print data,

        new_f.write(space)

    f.close()

2015/09/04 10:47

임 찬혁

가장 편한것은 command line에서,

expand -t 4 input_file > output_file

sed 사용 가능하면

sed $'s/\t/ /g' input_file > output_file

inplace원하면, vim에서

:%s/\t/ /g

혹은 sed에 -i를 씀

sed -i $'s/\t/ /g' input_file

2015/09/11 02:36

Jang Pilhoon

static void Main(string[] args)
        {
            string text = File.ReadAllText(@"E:\TebTest.txt");
            text = text.Replace('\t', ' ');
            text = text.Replace(" ", "    ");
            Console.WriteLine(text);
        }

2015/10/28 22:25

정우진

파이썬입니다. expandtabs 함수를 사용했습니다.

input_file = open('tab.txt', 'r')
output_file = open('space.txt', 'w')

def tabToSpace(text):   # 탭을 스페이스 4개로 바꾸는 함수
    return text.expandtabs(4)

text = input_file.read()
output_file.write(tabToSpace(text))

input_file.close()
output_file.close()

2015/11/03 15:53

김경호

//php

$file = fopen('./dojang.txt', 'r+'); while(!feof($file)) { $modi_file .= fgets($file); } fclose($file);

$modi_file = str_replace('\t', ' ', $modi_file);

$file = fopen('./m_dojang.txt', 'w'); fwrite($file, $modi_file);

2015/11/18 16:24

한기우

python3입니다. processDir()의 인자로 소스코드 디렉토리를 받도록 했습니다.

import os

def tab2space(filepath):
    fp = open(filepath, 'r')
    content = fp.read().replace("\t", " " * 4)
    fp.close()
    fp = open(filepath, "w")
    fp.write(content)
    fp.close()

def processDir(targetDir):
    for (root, _, files) in os.walk(targetDir):
        for file in files:
            tab2space(os.path.join(root, file))

2015/11/26 13:59

jspark

#include <stdio.h>
int main(int argc,char *argv[]){
        FILE *fp,*ap;
        int i;
        char a;
        if((fp=fopen(argv[1],"r"))==NULL)
                printf("오류:%s파일을 열수 없습니다.\n",argv[1]);
        if((ap=fopen(argv[2],"w"))==NULL)
                printf("오류:%s파일을 열수 없습니다.\n",argv[2]);
        while((a=getc(fp))!=EOF){
                if(a=='\t'){
                        a=' ';
                        for(i=0;i<3;i++){
                                putc(a,ap);
                        }
                }
                putc(a,ap);
        }
        fclose(fp);
        fclose(ap);
        return 0;
}

c언어 초보입니다 훈수부탁드립니다!!

2015/12/28 11:07

김종헌

파이썬 2.7.11

with open('test.txt') as f: s = f.read() s1 = s.replace('\t', ' ')

with open('test1.txt', 'w') as f: f.write(s1)

2015/12/29 16:54

hana11

import re
import sys

def insert():
    print("%s filename" % sys.argv[0])

try:
    f = open(sys.argv[1])
except:
    insert(); sys.exit(2)

msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*4, msg)

f = open(sys.argv[1], 'w')
f.write(changed)
f.close()

2016/01/03 15:34

한정민

하나하나씩 분석해보도록 하겠습니다.

filename=input("Enter your file name : ") // 이 줄은 input함수를 통해 키보드로부터 데이터를 입력받고 filename 변수에 저장합니다. tempfile=open(filename) // 키보드로부터 입력받은 데이터를 filename에 저장하고 temfile에 저장하고 파일을 오픈합니다. tempfile=tempfile.read() 오픈된 파일을 읽고 있습니다. temp_str=tempfile.replace("\t"," ") //여기서 문제에서 나온 \t개행문자를 공백문자 4개로 치환해주고있습니다. tempfile=open(filename,'w') // 여기서는 temfile을 쓰기모드로 오픈합니다. tempfile.write(temp_str) // temfile을 temp_str에서 수정한 내용을 복사하고있습니다. tempfile.close() // 파일을 닫습니다.

2016/01/08 15:00

Hitz

filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()

2016/01/09 15:16

Hitz

python 3.4

fname = input("Enter a file name :")
fhand = open(fname)
full_file = fhand.read().replace('\t','    ')
fhand = open(fname,'w')
fhand.write(full_file)
fhand.close()

2016/01/13 16:35

김 민성

def tab_to_spaces(text, spaces=4):
  return text.replace('\t', ' ' * spaces)

2016/01/13 16:58

곰세

import sys
text = open(sys.argv[1],'r').read().replace('\t','    ')
f=open(filename,'w')
f.write(text)
f.close()

2016/01/24 19:43

상파

sed -i 's/\t/    /g' 소스파일명

2016/02/14 18:41

Ji Hyeonho

# encoding=utf-8

save_f = open('text.txt', 'w+')

with open('test.txt', 'r') as f:
    for line in f.read():
        save_f.write(line.replace('\t',' '*4))

2016/02/16 18:08

Jeff An

Python newbie

tabFile = open("test.txt")
tmp = tabFile.read()
tabFile.close()
tmp = tmp.replace("\t", "    ")
spaceFile = open("test_new.txt", "w")
spaceFile.write(tmp)
spaceFile.close()

2016/03/09 15:43

rubbersoul

p = '경로'
with open(p, 'r') as temp:
    r = temp.read().replace('\t',' '*4)
with open(p, 'w') as ed:
    ed.write(r)

파이썬 3.5.1입니다.

2016/03/13 19:45

Flair Sizz

파이썬

def update(file):
    new_line = ''
    fin = open(file, 'rt')
    while True:
        line = fin.readline()
        if not line:
            break
        new_line += line.replace('\t', ' ' * 4, 100)
        #한 라인에 탭이 여러번 있을 수 있으므로 세번째 인자로 100번을 시행
    fin.close()

    fout = open(file, 'wt')
    fout.write(new_line)
    fout.close()

2016/03/18 17:23

디디

파이썬3.4

file = input()
with open(file) as filee:
    s = filee.read()
    s = s.replace('\t','    ')
with open(file, 'w') as filee:
    filee.write(s)

2016/04/17 00:23

차우정

Ruby

conv = ->code { code.gsub("\t", "    ") }
cleanse = ->src { File.open(src,'r+') {|f| f.write(conv[File.read(src)]) } }
#=> cleanse["source file"]

Test

expect(conv["\t"]).to eq "   "

2016/04/18 00:09

rk

C#으로 작성했습니다.

        public string PrintToSpaces(string input)
        {
            return input.Replace("\t", " ").Replace(" ",string.Empty.PadLeft(4));
        }

2016/04/19 09:11

Straß Böhm Jäger

out_filename = "result.py"
filename = input("filename: ")
try:
    with open(filename) as f:
        data = f.read()
        with open(out_filename, 'w') as new_file:
            new_file.write(data.replace('\t', '    '))
            print("write ", out_filename)
except IOError as error:
    print(str(error))

2016/04/27 14:01

SanghoSeo

import os

def tab_to_space(path, ext='py', space_count=4):
    def _update(full_path):
        with open(full_path, 'r+') as f:
            new_code = _tab_to_space(f.read())
            f.seek(0)
            f.write(new_code)
    _tab_to_space = lambda code: code.replace('\t', ' ' * space_count)
    dot_ext = '.' + ext
    [_update(os.path.join(dp, fn)) for dp, dn, fns in os.walk(path) for fn in fns if not dn and fn.endswith(dot_ext)]

2016/05/04 19:27

Park Ohyoung

the_file = open("the_file.txt", "r")
new_file = open("new_file.txt", "w")

lines = ''

for text in the_file.readlines():
    for t in text:
        if t == '\t':
            lines += '    '
        else:
            lines += t
new_file.write(lines)

the_file.close()
new_file.close()

2016/05/07 22:57

C13H12N4O2

import re
a=open("1.txt","r")
b=a.read()
c=re.compile(r".*\t.*",re.DOTALL)
print(c.sub("-",b))

2016/05/08 18:37

Dr.Choi

파이썬입니다.

open('output.txt', 'w').write(''.join([x.replace('\t', ' ' * 4) for x in open('input.txt', 'r').readlines()]))

2016/05/19 15:02

choo dg

Python 3.5

def tab_to_spaces(text):
    text.replace('\t', '    ')

2016/05/20 00:57

Analyticsstory

자바로 만들었습니다 .. 매우 단순합니다..

package javaCoding;

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List;

public class Coding003 {

public static void main(String[] args) {


    FileReader file=null;

    BufferedReader buffer=null;

    String AA=null;

    StringBuffer BB=new StringBuffer();



    try {       
        //경로 읽기.
        file=new FileReader("D:/sdf.txt");

        //읽고 나는 버퍼더 리더에 넣을꺼다.
        //왜 ?? file의 읽은 값을 받아들이는 것줄에 버퍼더리더가 아주 바람직함.
        buffer=new BufferedReader(file);

        //버퍼.리드라인 = 택스트에 한줄한줄 읽음서 유무를 확인하면서 .. 스트링 빌더에 넣고있음.
    while((AA=buffer.readLine())!=null) {

        BB.append(AA);

    }

    //BB.indexOf("  ") =>텝하나를 의미함..

    while((BB.indexOf(" ")>0)) {
    BB.replace(BB.indexOf(" "),BB.indexOf(" ")+1,"    ");
    }

    System.out.println(BB);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /////////////////////////////////////////////////////////////////////

    //위 바꾼 값을 txt로 다시 새롭게 만들기.

    //스트링 버퍼의 값을 to스트링을 통해서 스트링으로 변환 해줌 ..
    String txt=BB.toString();

    //경로
    String txt2="D:/hahah.txt";

    //경로 파일에 담기
    File file2=new File(txt2);
    try {

        //파일 쓰기
        FileWriter file3=new FileWriter(file2);

        //값입력
        file3.write(txt);
        //넣고
        file3.flush();
        //닫고
        file3.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

}

2016/05/28 16:10

정 성훈

Java로 작성된 코드입니다.

import java.util.Scanner;

public class TabToSpace {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();
        str.replaceAll("\t", "    ");

        System.out.println(str);
    }
}

2016/06/04 16:01

손 량

package main

import (
    "io/ioutil"
    "bytes"
    "os"
    "fmt"
)

func main() {
    var in_file, out_file string

    fmt.Print("Input File Name: ")
    fmt.Scan(&in_file)

    fmt.Print("Output File Name: ")
    fmt.Scan(&out_file)

    if rb, error := ioutil.ReadFile(in_file); error == nil {
        wb := []byte(rb)
        wb = bytes.Replace(wb, []byte("\t"), []byte("    "), -1)
        ioutil.WriteFile(out_file, wb, os.ModePerm)
    }
}

2016/06/15 22:31

uuuuuup

Scanner scan = new Scanner(System.in);
System.out.println("문자를 입력해주세요");

String text = scan.nextLine();
text = text.replaceAll("\t", "    ");

System.out.println(text);

2016/06/17 12:23

김 수영

package 코딩도장;

public class Q4 {

public static void main(String[] args){
     String text = "Good\tSoGood\t";
     String replace = text.replaceAll("\t", "    ");
     System.out.println(text);
     System.out.println(replace);        
}

}

2016/07/08 18:26

서동빈

Python

def code(c):
    for i in c:
        if i=="\t":
            c.replace(i,"    ")
        else:
            pass
    print(c)

code("여기에\t코드를\t붙여넣으면\t됨")

2016/07/09 01:25

왈왈

자바로 코딩
1. reaplce
2. char 배열에 저장 해서 출력

    public static void main(String[] args){

        try{

            String tab = "테스트   입니다 ";

            tab = tab.replace("\t", "    ");

            char[] ch = tab.toCharArray();
            for(int i=0; i<ch.length; i++){
                System.out.print( i + " " + " :: ==> " + (int)ch[i] + "\t" + " || ");
                System.out.print( i + " " + " :: ==> " + ch[i] );
                System.out.println("");
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }

2016/07/15 16:13

황 정석

자바로 코딩
파일을 읽는 다는 가정하에 만들었습니다.

    public static void main(String[] args){

        try{

            // 파일 읽기
            File file = new File("c:\\test.txt");
            FileInputStream fis     = new FileInputStream(file);
            InputStreamReader isr   = new InputStreamReader(fis,"UTF-8");
            BufferedReader br       = new BufferedReader(isr);

            // 파일 쓰기
            FileOutputStream fos = new FileOutputStream("c:\\test1111.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");

            String str = "";
            while( (str=br.readLine()) != null ){
                str = str.replace("\t", "    ");
                osw.write(str);
                osw.write("\n");
            }

            // close
            fis.close();
            isr.close();
            br.close();
            osw.close();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

2016/07/15 17:06

황 정석

private static String source="Source\tEx\tcoingdojang\tzzz";
    public static void main(String[] args) {
        System.out.println(source);
        System.out.println(source.replace("\t"," "));
    }

2016/07/26 11:29

Oh Tae Gyeoung

        String m = "왜\t하기도\t힘든\t실수를해서...\t";
        String re = m.replaceAll("\t","    ");
        System.out.println(re);

2016/07/26 14:38

김치영

  • javascript 언어 사용
var str = "안녕하세요.       ㅋㅋㅋㅋㅋㅋ      ㅎㅎㅎㅎㅎㅎㅎ";

// tab이 포함된 문자열인지 확인
// 결과값 : true
console.log(/\t/gi.test( str ));
// 공백(space) 포함된 문자열인지 확인
// 결과값 : false 
console.log(/ /gi.test( str ));

// tab -> space 4번으로 변경
str = str.replace(/\t/gi, "    ");

// 결과값 : false
console.log(/\t/gi.test( str ));
// 결과값 : true 
console.log(/ /gi.test( str ));

2016/08/08 12:06

song ah-young

python 3.5


def change_tab_to_space(src):
    with open(src, 'r') as f:
        data = f.read()

    with open(src, 'w') as f:
        f.write(data.replace("\t", " "*4))

change_tab_to_space("a.txt")

2016/08/09 22:36

정 우순

vim

:set tabstop=4 expandtab
:%retab!

2016/08/14 17:07

Kim

static void Main(string[] args)
        {

            string tab = "\t";

            tab =  tab.Replace("\t", "");

                 }
    }

2016/08/15 21:51

송 기태

def TabToSpaceConverter(orginalSouce):
    newSource = ""
    for i in orginalSouce:
        if i == '\t':
            newSource += "    "
        else:
            newSource += i

    return newSource

print(TabToSpaceConverter(source))

2016/08/26 09:09

Kim Sean

#include <iostream>
#include <string>
#include <algorithm>

std::string sample = "haha\tnice to meet\tyou";

int main() {
    std::cout << sample << std::endl;
    while (sample.find("\t") != std::string::npos)
    {
        sample = sample.replace(sample.find("\t"), 1, "    ");
    }
    std::cout << sample << std::endl;
    return 0;
}

c++ 작성

2016/08/30 02:54

정 태석

python 2.7.12

with open('./level1/input.txt','r+') as f:
        print f.read().replace("\t"," "*4)

2016/09/03 19:07

happygrammer

#include <stdio.h>

int main(){
    FILE* pfa;
    FILE* pfb;

    pfa = fopen("a.c", "r");
    pfb = fopen("b.c", "w");

    char c;
    while((c = getc(pfa)) != EOF){
        if(c == '\t'){
            putc(' ', pfb);
            putc(' ', pfb);
            putc(' ', pfb);
            putc(' ', pfb);
        } else {
            putc(c, pfb);
        }
    }
    fclose(pfb);
    fclose(pfa);
}

2016/09/15 14:01

이 종성

import re
import sys

def insert():
    print("%s filename" % sys.argv[0])

try:
    f = open(sys.argv[1])
except:
    insert(); sys.exit(2)

msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*4, msg)

f = open(sys.argv[1], 'w')
f.write(changed)
f.close()

2016/09/21 15:45

머얼씨

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TabtoWhiteSpace {
    public static void main(String args[]) {
        String path = "C:/Users/woo/workspace/20161006/test.txt";
        String path2 = "C:/Users/woo/workspace/20161006/out.txt";

        try{
            BufferedReader in = new BufferedReader(new FileReader (path));
            BufferedWriter out = new BufferedWriter(new FileWriter (path2));
            String s;
            while ((s = in.readLine()) != null) {

                if(s.contains("\t")) {
                    s = s.replace("\t", "    ");
                    out.write(s+"\r\n");
                } else {
                    out.write(s+"\r\n");
                    //out.write("hello world");
                }
            }
            out.close();
        } 
        catch(IOException e) {
            System.err.println(e);
            System.exit(1);
        }
    }
}

2016/10/05 18:51

코딩초보

파이썬

import sys

fromFile = sys.argv[1]
toFile = sys.argv[2]

f = open(fromFile)
origin_content = f.read()
f.close()

replace_content = origin_content.replace("\t", " " * 4)

f = open(toFile, 'w')
f.write(replace_content)
f.close

2016/10/17 09:19

훠니

f = open("D:/python/test.txt", 'r')

while True:
    line = f.readline()
    if not line: break

    if line[0] == "\t":
        line = "    " + line[1:]
    print(line)
f.close()

2016/11/02 13:03

mch

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
    string temp;
    vector<string> v_temp;
    ifstream fin;
    ofstream fout;


    fin.open("insert.txt");
    fout.open("result.txt");

    while(!fin.eof()) {
        getline(fin, temp);
        v_temp.push_back(temp);
    }

    for (int counter = 0; counter < v_temp.size(); counter++) {
        temp = v_temp[counter];

        if (temp[0] == '\t') {
            temp.erase(0, '\t');
            temp.insert(0,"    ");
        }

        fout << temp << endl;
    }

    fin.close();
    fout.close();

    return 0;
}

2016/11/02 17:23

seo bum seok

Java

  • 대상 폴더 및 하위 폴더 파일 각 라인의 처음에 있는 탭만 스페이스 4개로 바꾸어 저장
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;

public class TabToSpaceTester {

    public static UnaryOperator<String> precedingTabToSpace = s -> {
        if (s == null || s.length() == 0) return s;
        StringBuffer result = new StringBuffer();
        boolean isPrecedingTab = s.startsWith("\t");
        int pos = 0;
        while (isPrecedingTab && pos < s.length() && s.charAt(pos) == '\t') {
            result.append("    ");
            pos++;
        }
        if (pos < s.length() - 1) {
            result.append(s.substring(pos));
        }
        result.append(System.lineSeparator());
        return result.toString();
    };

    public static Consumer<Path> convertFile = p -> {
        File tempFile = new File(p.toString() + ".tmp");
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile)))) {
            try (Stream<String> stream = Files.lines(p)) {
                stream.map(precedingTabToSpace)
                        .forEach(line -> {
                            try { writer.write(line); } catch (IOException e) { e.printStackTrace(); }
                        });
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (p.toFile().delete()) {
            tempFile.renameTo(p.toFile());
        } else {
            tempFile.delete();
        }
    };

    public static void main(String[] args) throws IOException {
        try (Scanner sc = new Scanner(System.in)) {
            Path srcPath = Paths.get(sc.nextLine());
            Files.walk(srcPath).filter(p->p.toFile().isFile()).forEach(convertFile);
        }
    }
}

2016/11/03 03:27

compert

탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는...

먼저 복사하는 프로그램.

int main(int argc, const char * argv[]) {
    int c;
    while ((c=getchar()) != EOF) {
        putchar(c);
    }
    return 0;
}

그럼 탭을 공백 4개로..

        if (c == '\t') {
            putchar(' ');
            putchar(' ');
            putchar(' ');
            putchar(' ');
        } else {
            putchar(c);
        }

2016/11/03 22:02

Han Jooyung

Replace 메소드 안쓰고 짜봤습니다. 각 줄 소스 앞의 탭만 제거

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class ReplaceTap {

    public static void main(String[] args) {
    }

    public String[] replaceTap(final String[] codes) {
        String[] result = new String[codes.length];
        final String blank = "    ";

        for (int stringIndex = 0; stringIndex < codes.length; stringIndex++) {
            int count = 0;
            int codeStart = 0;
            result[stringIndex] = new String();

            for(int i = 0; i < codes[stringIndex].length(); i++) {
                char ch = codes[stringIndex].charAt(i);

                if(ch == '\t') {
                    count++;
                    codeStart = i;
                } else 
                    break;
            }

            for(int i = 0; i < count; i++)
                result[stringIndex] += blank;

            result[stringIndex] += codes[stringIndex].substring(codeStart + 1);
        }

        return result;
    }

    @Test
    public void testReplaceTap() {
        String[] code = new String[] {"\tprint()" , "\t\texit()"};
        String[] expectedString  = new String[] {"    print()", "        exit()"};

        assertArrayEquals(expectedString, replaceTap(code));
    }
}

2016/11/04 15:13

한비타

def convert_tab_to_space(src, dest):
    ''' 텍스트파일의 탭문자를 공백문자 4개로 바꾼다 '''
    with open(src, 'r', encoding='utf-8') as source:
        txt = source.read()

    with open(dest, 'w', encoding='utf-8') as destination:
        destination.write(txt.replace('\t', '    '))

2016/11/18 17:33

박인기

import re
def replaceTab(source):
    p = re.compile(r'^(\t+)', re.M)
    return p.sub(lambda m:m.group(1).replace('\t', '    '), source)

2016/11/22 15:10

Yeo HyungGoo

                String str="aaa\taaa\taaa";

        String strResult = "";

        System.out.println(str);


        for(int i = 0; i < str.length(); i++){

            strResult += ('\t' == str.charAt(i))?"    ":str.charAt(i);

        }



        System.out.println(strResult);

2016/11/22 22:37

francis

Scanner로 입력받은 문자열을 replaceAll 메소드로 변경

import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.print("Input:");
        Scanner obj=new Scanner(System.in);
        String str=obj.nextLine();
        System.out.println("Before:"+str);
        str=str.replaceAll("\t", "    ");
        System.out.println("After"+str);
    }

}

2016/11/24 18:01

신 동리

Haskell

import System.Environment
import Control.Monad


tabToSpace line =
    case line of
        '\t':xs -> "    " ++ (tabToSpace xs)
        otherwise -> line

main = do
    inputFile <- getArgs
    let filename = if inputFile == [] then "example.txt" else inputFile !! 0
    contents <- readFile filename
    let result = unlines $ fmap (tabToSpace) (lines contents)
    writeFile ("New_" ++ filename) result

2016/12/01 00:34

윤태호

def Change_to_space(string):
    return string.replace('\t',' '*4)

#### 2016.12.09 D-440 ####


2016/12/09 22:27

GunBang

위키독스의 점프 투 파이썬 중

a.txt라는 파일에 있는 탭을 4개의 공백으로 바꾸어 b.txt라는 파일에 저장하고 싶다면 다음과 같이 수행해야 한다.

python tabto4.py a.txt b.txt 1. 우선 다음과 같이 tabto4.py 파일을 작성해 보자.

(※ tabto4.py는 C:\Python 디렉터리에 저장한다.)

# c:/Python/tabto4.py
import sys

src = sys.argv[1]
dst = sys.argv[2]

print(src)
print(dst)

sys.argv를 이용하여 입력값을 확인하도록 만든 코드이다.

  1. 다음과 같이 수행했을 때 입력값들이 정상적으로 출력되는지 확인해 보자.

C:\Python>python tabto4.py a.txt b.txt a.txt b.txt 입력으로 전달한 a.txt와 b.txt가 정상적으로 출력되는 것을 확인할 수 있다.

  1. 테스트를 위한 원본 파일(탭을 포함하는 파일)인 a.txt를 다음과 같이 작성한다. 각 단어들은 탭(\t) 문자로 분리되도록 입력해야 한다.

Life is too short You need python 4. 이제 탭 문자를 포함한 a.txt 파일을 읽어서 탭을 공백 4개로 변환할 수 있도록 코드를 변경해 보자.

# c:/Python/tabto4.py
import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)
print(space_content)

위 코드는 src에 해당되는 입력 파일을 읽어서 그 내용을 tab_content라는 변수에 저장한 후 문자열의 replace 함수를 이용하여 탭(\t)을 4개의 공백으로 변경하는 코드이다.

  1. tabto4.py를 위와 같이 변경한 후 다음과 같은 명령을 수행해 보자.

C:\Python>python tabto4.py a.txt b.txt Life is too short You need python 아마도 탭 문자가 공백 4개로 변경되어 출력될 것이다. 하지만 탭과 공백의 차이점을 눈으로 확인할 수는 없으므로 탭이 정상적으로 공백으로 변경되었는지 확인하기 어렵다.

  1. 이제 변경된 내용을 b.txt 파일에 저장할 수 있도록 다음과 같이 프로그램을 변경해 보자.
# c:/Python/tabto4.py
import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open(dst, 'w')
f.write(space_content)
f.close()

탭이 공백으로 변경된 space_content를 출력 파일인 dst에 쓰도록 코드를 수정하였다.

  1. 프로그램을 실행하기 위해 다음과 같은 명령을 수행한다.

C:\Python>python tabto4.py a.txt b.txt 위 명령을 수행하면 b.txt 파일이 C:\Python 디렉터리에 생성된다. 에디터로 b.txt 파일을 열어서 탭이 4개의 공백 문자로 변경되었는지 확인해 보자. 프로그램 작성 시 사용하는 에디터는 대부분 탭과 공백 문자를 다르게 표시하므로 눈으로 확인이 가능할 것이다.

저작권은 박응용씨한테 있습니다.

2016/12/12 16:43

김동우

public class TabTo4Space { public static void main(String[] args) throws IOException{

    FileInputStream originalFis = null;
    FileOutputStream outputFis = null;
    try{
        originalFis = new FileInputStream(new File("D:/temp/String.java"));
        outputFis = new FileOutputStream(new File("D:/temp/StringOutput.java"));
        int readValue = 0;
        while((readValue = originalFis.read())!= -1){
            char character = (char)readValue;
            if(character =='\t'){
                outputFis.write(' ');
                outputFis.write(' ');
                outputFis.write(' ');
                outputFis.write(' ');
            }else{
                outputFis.write(readValue);
            }

        }

    }catch(IOException ioe){

    }finally{
        if(originalFis != null){
            originalFis.close();
        }
        if(outputFis != null){
            originalFis.close();
        }
    }


}

}

2016/12/25 12:27

초급



#with 사용시 file open/close 필요 X
# "    "  보다는  " " * 4가 더 가독성이 좋음


with open('output.txt',"wb") as wp:
    with open("input.txt",'rb') as rp:
        for line_no,line in enumerate(rp):
            replaced = line.replace("\t", " " * 4)
            writeline = wp.write(replaced)

2016/12/28 17:21

Daniel

파이썬 3.x 기준 변환할 파일을 입력하고, 새로 저장할 이름을 입력하여 만들었습니다.

# -*- coding: utf-8 -*- 
# 파일을 읽어서 탭을 공백4개로 치환
name = input('Read file name : ')
new = input('Save file name : ')
f = open(name, 'r')
tab = f.read()
space = tab.replace("\t", " "*4)
f.close()
f = open(new, 'w')
f.write(space)
f.close()

2017/01/01 17:46

주 현태

var str = "안녕하세요            ㅇㅇ      ㅇㅇ  ㄴㄷ";
str = str.replace(/\t/gi, '    ');

2017/01/20 10:46

권혁기

from functools import reduce

def space4indent(address):
    text=open(address, "r+")
    ls=text.readlines()
    result=reduce(lambda x,y: x+"".join(map(lambda x: x.replace("\t","    ",1), y)), ls)
    text.close()
    file=open("text.py", "w");file.write(result);file.close()

space4indent("text.py")

2017/01/25 17:55

Song Seoha

src=open('file.txt','r')
dst=open('dest.txt','a')

lines = src.readlines()

for line in lines:
    dst.write(line.replace("\t"," "*4))

2017/02/19 00:31

Scott.Jun

import codecs
with codecs.open('a.txt', 'r', 'utf8') as read_file:
    with codecs.open('a_.txt', 'w', 'utf8') as write_file:
        for row in read_file:
            write_file.write(row.replace('\t', '    '))

2017/02/19 19:41

jackson

import codecs
with codecs.open('a.txt', 'r', 'utf8') as read_file:
    with codecs.open('a_.txt', 'w', 'utf8') as write_file:
        for row in read_file:
            write_file.write(row.replace('\t', '    '))

2017/02/19 19:41

jackson

  • python : 3.5.2

  • answer is ...

filename = input('filename ? ')
new_filename = filename + '.new'

file = open(filename, 'r')
new_file = open(new_filename, 'w')

for i in file :
    changes = i.replace('\t', '    ')
    new_file.write(changes)

file.close()
new_file.close()

2017/02/23 10:52

강정민

파이썬

inp1 = input("파일명 입력: ")
f = open(inp1)
a = f.read()
f.close()

f = open(inp1,'w')
f.write(a.replace("\t","    "))
f.close

2017/03/02 04:31

황인우

파이썬 3.6 (replace 안쓴 풀이)

f = open("파일경로/파일이름", 'r') #파일을 불러서 엽니다.
while True: #반복문을 실행합니다.
    line = f.readline() #파일에 작성된 코드를 한줄씩 문자열 형태로 읽어옵니다.
    if not line: break #더이상 읽어올 줄이 없으면 반복문을 종료합니다.
    snts = "" #임의의 변수에 빈 문자열을 담아둡니다.
    for i in line: #읽어온 한줄을 한글자씩 확인하는데,
        if i == '\t': #이때 탭(\t)이 있으면
            i = '____' #띄워쓰기 4칸으로 바꿔줍니다. (눈에 더잘띄라고 _로했습니다.)
        snts += i #확인(?)을 마친 한글자씩 변수에 담고,
    print(snts) #한문장씩 출력합니다.
f.close() #파일을 닫습니다.

전형적인 입문자 수준의 코드입니다. 파일을 읽어와서 출력하는 프로그램입니다. 파일 열고 닫는게 미흡해서 출력하는 수준으로 했구요. replace함수 안쓰고 해보려고 노력했습니다.

2017/03/13 20:41

cano

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class TabConverterSpace {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(new File(""));
        PrintWriter pw = new PrintWriter(new File(""));

        while (sc.hasNext()) {
            String a = sc.nextLine();
            pw.println(a.replaceAll("   ", "    "));
        }

        sc.close();
        pw.close();
    }
}

2017/03/18 00:28

genius.choi

package training;

public class ReplaceTapToSpace {
    public static void main(String[] args) {
        String strSample = "Hello\tWorld";
        String strResult = strSample.replaceAll("\t", "    ");
        System.out.println("org text : " +strSample );
        System.out.println("cov text : " +strResult );
    }
}

2017/03/31 15:08

acedo

replace를 쓰지 않으려고 했습니다.

def tap_to_space(doc):
    return '    '.join(doc.split('\t'))

2017/04/05 15:27

soleaf

def tap_to_4space(code):
    result = ""
    for i in code:
        if i == '\t':
            result += "    "
        else:
            result += i
    return result


f = open("original.txt", 'r')
code1 = f.read()
f.close()

result1 = tap_to_4space(code1)

f = open("result.txt", 'w')
f.write(result1)
f.close()

파이썬 3.5입니다. 탭을 4개의 space로 변경하기 원하는 원본코드 파일의 내용 전체를 read()함수를 사용해서 문자열로 리턴한 다음, 그 문자열의 처음부터 끝까지 체크하면서 탭이 들어간 부분은 4개의 space로 바꿔줬습니다. 그리고 result.txt에 변환된 결과를 출력시켰습니다. 구현하고 나서 풀이해놓으신 것들을 살펴보니, replace() 함수를 사용하면 훨씬 간단하군요.^^;; 이상 파이썬 초보의 문제풀이였습니다.

2017/04/06 22:13

simkyohoon

f = open('file.txt', 'r')
a = f.read()
b = a.replace("/t", "    ")
f = open('file.txt', 'w')
f.write(b)
f.close()

2017/04/09 16:58

Hyung-Woo Ryoo

#include <stdio.h>
#include <string.h>

static FILE *_open_file(const char *ppath, const char *pmode);
static int _close_file(FILE **ppfile);
static int _change_tap_to_blank_func(FILE *pread, FILE *pwrite);

///////////////////////////////////////////////////////////////////////////////

static FILE *_open_file(const char *ppath, const char *pmode)
{
    FILE *pnew = fopen(ppath, pmode);
    if (pnew == NULL)
    {
        printf("[ERR] Fail to file open. %s %s %d\n",
                __FILE__, __func__, __LINE__);
        goto error;
    }

error :
    return pnew;
}

static int _close_file(FILE **ppfile)
{
    if (ppfile == NULL)
    {
        printf("[ERR] File points NULL status already. %s %s %d\n",
                __FILE__, __func__, __LINE__);
        goto error;
    }

    if (*ppfile)
    {
        fclose(*ppfile);
        *ppfile = NULL;
    }

    return 0;

error :
    return -1;
}

static int _change_tap_to_blank_func(FILE *pread, FILE *pwrite)
{
    int i;
    int len;
    char str[512] = {0, };

    while (fgets(str, sizeof(str), pread))
    {
        str[strlen(str) - 1] = '\0';
        len = strlen(str);

        for (i = 0; i < len; i++)
        {
            (str[i] == '\t') ? 
                fprintf(pwrite, "    ") : 
                fprintf(pwrite, "%c", str[i]);
        }
        fprintf(pwrite, "\n");
    }

    return 0;
}

int main(void)
{
    FILE *pread = _open_file("tap_to_blank.c", "r");
    if (pread == NULL)
        goto error;

    FILE *pwrite = _open_file("new_file", "w");
    if (pwrite == NULL)
        goto error;

    _change_tap_to_blank_func(pread, pwrite);

error :
    _close_file(&pwrite);
    _close_file(&pread);

    return 0;
}

c언어로 구현했습니다. tap_to_blank.c 파일을 읽어서 new_file로 변경하면서 탭을 공백4칸으로 변경 합니다.

2017/04/09 19:19

by코딩요정

python 3.4.2

import sys

old_file_name = sys.argv[1]
new_file_name = sys.argv[2]

old_file = open(old_file_name)
old_file_str = old_file.read()
old_file.close()

new_file_str = old_file_str.replace("\t", " "*4)

new_file = open(new_file_name, "w")
new_file.write(new_file_str)
new_file.close()

변환방식은 명령행 뒤에 argument 로


pi@raspberrypi:~/example $ sudo python3 tab4spaces.py eg_source.txt.py no_tab.py
pi@raspberrypi:~/example $ cat no_tab.py
    tab
    4spaces
        tab+4spaces
        tab+tab
            tab+tab+4sapces
            tab+tab+tab
                tab*4

2017/04/11 06:45

예강효빠

아래 내용을 test.py라고 저장했을 경우

cmd에서 c:>python test.py abc def 라고 입력하면 abc이 있는 탭을 모두 스페이스 4개로 바꿔서 def로 저장하도록 만든 것입니다.

# coding = utf-8

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src,"r")
tempfile = f.read()
replacefile = tempfile.replace("\t","    ")
f.close()

dst = open(dst,"w")
dst.write(replacefile)
dst.close()


2017/05/09 22:18

최준호

어렵군요 ㅜㅜ

import java.io.*;

public class TabtoSpace{
    public static void main(String[] args){
        TabtoSpace ts = new TabtoSpace();

        String curdir = System.getProperty("user.dir");

        String filename = ts.findfile(curdir);

        if(filename.equals("no"))
            System.out.println();
        else
            ts.toSpace(filename);   

    }

    String findfile(String filename){
        File f = new File(filename);


        String[] lists = f.list();
        for(int i=0;i<lists.length;i++){
            if(lists[i].endsWith(".java"))
                return lists[i];
        }

        return "no";

    }

    void toSpace(String filename){
        File f = new File(filename);
        try{
            FileReader reader = new FileReader(f);
            FileWriter writer = new FileWriter("output.txt");
            int get_asc=0;

            while((get_asc=reader.read())!=-1){
                char get_char = (char)get_asc;
                if(get_char =='\t'){
                    get_char=' ';
                    for(int i=0;i<4;i++){
                        writer.write(get_char);
                    }
                }
                else{
                    writer.write(get_char);
                }
            }
            writer.close(); 
            reader.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }
}

2017/05/10 19:00

CHIJE PARK

def ftspace(F):

f = open(F, 'r')
R = open("Newtext.txt", 'w')

while True:
    line = f.readline()
    if not line:
        break
    for i in line:
        if i == '\t':
            line = line.replace('\t', '    ', 1)
        elif i != '\t':
            break

    R.write(line)
f.close()
R.close()

2017/05/23 00:57

김순효

c로 풀이.

#include <stdio.h>
int main(void)
{
    int m;
    FILE*fp,*fp2;
    char file_name[10],new_file[10];
    printf("열 파일 이름 : ");
    scanf("%s",file_name);
    fp=fopen(file_name,"r");
    printf("작성할 파일 이름 : ");
    scanf("%s",new_file);
    fp2=fopen(new_file,"w");
    while(!feof(fp))
    {
        m=fgetc(fp);
        if (m==9) fprintf(fp2,"    ");
        else fputc(m,fp2);
    }
    printf("%d",'\t');
    fclose(fp);
    fclose(fp2);
    return 0;
}

2017/06/02 16:41

박동준

public class TabReplaceSpace {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("1\t2\t3\t4\t5\n");
        sb.append("1\t2\t3\t4\t5\n");
        sb.append("1\t2\t3\t4\t5\n");
        // (숫자 5글자 + 특수문자(탭/엔터) 5글자) * 3줄 = 30
        System.out.println("길이 : " + sb.toString().length());
        System.out.println(sb.toString() + "\n");

        String str  = sb.toString();
        // str = str.replaceAll("\\t", "...."); // 이것!!!
        str = str.replaceAll("\\t", "    "); // 이것!!!

        // (숫자 5글자 + 특수문자(엔터) 1글자 + 공백 16) * 3줄 = 66
        System.out.println("길이 : " + str.length());
        System.out.println(str);
    }
}

2017/06/02 17:18

김중운

import os

def change_text(filename):
    f=open(filename,'r')
    while True:
        line=f.readline()
        if not line:
            break
        list_line=list(line)
        for i in range(len(list_line)):
            if list_line[i] == "\t":
                del list_line[i]
                list_line.insert(i,"    ")
        list_line="".join(list_line)
        print(list_line)


    f.close()
dirname="C:/test/test.txt"
change_text(dirname)

2017/06/13 15:12

나후승

Replace를 최대한 피해서 작성했습니다. 직접 입력하는 방식이죠. C입니다.

// 탭 바꾸기 - C
#include <stdio.h>
#include <string.h>
int main(void)
{
    char text[16384]; int i, j; char temp[16384];
    printf("Ready>>>\n");
    gets(text);
    strcpy(temp, text);
    for (i = 0; i < 16384; i++)
    {
        if (text[i] == '\t')
        {
            for (j = 0; j < 4; j++)
                text[i + j] = ' ';
            for (j = i; j < 16380; j++)
                text[j + 4] = temp[j + 1];
            strcpy(temp, text);
        }
        if (text[i] == '\0')
            break;
    }
    puts(text);
}

2017/06/27 22:08

Jeong Hoon Lee

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

string indent_tabTospace(const string &strLine)
{
    string strTemp = strLine;
    int cnt_tabs = 0;

    for (int i = 0; i < strTemp.length(); i++) {
        if (strTemp[i] == '\t') 
            cnt_tabs += 1;
         else
            break;
    }
    strTemp.erase(0, cnt_tabs);

    for (int i = 0; i < cnt_tabs; i++)  
        strTemp.insert(0, "    ");

    return strTemp; 
}

int main(int argc, char** argv)
{
    ifstream fin;
    ofstream fout;
    string strTemp  = "";

    fin.open(argv[1]);
    fout.open("output.txt"); 

    vector<string> lineString;

    while(!fin.eof())
    {
        getline(fin, strTemp);
        lineString.push_back(strTemp);
    }

    for ( auto s : lineString )
    {
        strTemp  = indent_tabTospace(s);
        fout << strTemp << endl;;
    }

    fin.close();
    fout.close();

    return 0;
}

2017/06/30 11:32

Logan

def make_str(chr, num_of_chr):
    result = ''.join([' ' for i in range(num_of_chr)])
    #for i in range(num_of_chr):
    #    result += chr
    return result

def tab_to_space(code, num_of_space):
    str_space = make_str(' ', num_of_space)
    code = code.replace('\t', str_space)
    return code

2017/07/01 11:48

이정환

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

string indent_tabTospace(const string &strLine)
{
    string strTemp = strLine;
    int cnt_tabs = 0;

    //for (int i = 0; i < strTemp.length(); i++) {
    for (int i = 0; i < strTemp.length(); i++) {
        if (strTemp[i] == '\t') 
            cnt_tabs += 1;
         else
            break;
    }
    strTemp.erase(0, cnt_tabs);

    for (int i = 0; i < cnt_tabs; i++)  
        strTemp.insert(0, "    ");

    return strTemp; 
}

int main(int argc, char** argv)
{
    ifstream fin;
    ofstream fout;
    string strTemp  = "";

    fin.open(argv[1]);
    fout.open("output.txt"); 

    vector<string> lineString;

    while(!fin.eof())
    {
        getline(fin, strTemp);
        lineString.push_back(strTemp);
    }

    for ( auto s : lineString )
    {
        strTemp  = indent_tabTospace(s);
        fout << strTemp << endl;;
    }

    fin.close();
    fout.close();

    return 0;
}

2017/07/03 09:58

Logan

정규식

import re

def noop():
    def noop2():
        pass
    def noop3():
        def noop4():
            if True:
                pass
            else:
                pass
    pass


me = open(__file__).read()
print(re.sub(r'^\t+', lambda m: '....'*len(m.group()), me, flags=re.MULTILINE))

그냥

def tab_to_space(srcfile):
    code = []
    with open(srcfile, 'r') as f:
        while True:
            line = f.readline()
            if not line:
                break

            tabcnt = 0
            for char in line:
                if char == '\t':
                    tabcnt += 1
                else:
                    break

            code.append('    ' * tabcnt + line[tabcnt:])

    return ''.join(code)

2017/07/03 14:46

Noname

JAVA입니다.

public class Ex011 {
    static char[] str = null;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //소스코드 입력
        getInputData();

        //작업 및 출력
        tab2space();
        System.out.println();
        System.out.print("결과: ");
        System.out.println(str);

    }

    //탭문자 -> 공백문자
    static private void tab2space() {
        for(int i = 0; i < str.length; i++) {
            //탐색 중 탭문자가 나온다면 배열늘리고 탭문자->공백문자
            if(str[i] == '\t') {
                //배열 늘리고
                str = spanArray(i);
                //공백문자로 대체
                str[i] = ' ';
                str[i+1] = ' ';
                str[i+2] = ' ';
                str[i+3] = ' ';
                System.out.print("공백문자대체후      : ");
                System.out.println(str);
            }
        }
    }

    //배열 크기 늘리고 공백문자 들어갈 자리 비워두기(+3)
    static private char[] spanArray(int repIdx) {
        char[] span = new char[str.length+3];
        int curIdx = 0;
        for(int i=0; i < str.length; i++,curIdx++) {
            span[curIdx] = str[i];
            //탭이 발견된 위치에 도달하면 공백문자 들어갈 공간만큼 비운다.
            if(i == repIdx)
                curIdx+=3;
        }
        System.out.println();
        System.out.print("배열확장및공간만듦: ");
        System.out.println(str);
        return span;
    }

    //소스코드(문자열) 입력
    static private void getInputData() {
        Scanner scan = new Scanner(System.in);
        System.out.print("소스코드입력~: ");
        String input = scan.nextLine();
        str = input.toCharArray();

    }
}

String 이나 StringBuffer,StringBuilder 이용하지 않고 배열로 구현해보았습니다.

입력값에는 공백문자는 없으며 탭문자를 두번 넣었습니다. <결과> 소스코드입력~: abc def ghi

배열확장및공간만듦: abc def ghi 공백문자대체후 : abc def ghi

배열확장및공간만듦: abc def ghi 공백문자대체후 : abc def ghi

결과: abc def ghi

2017/07/05 00:57

pg

Python 3 으로 풀었습니다.

def solve(s):
    return s.replace('\t', '    ')

2017/07/06 16:03

SOUP

python 3.6을 이용했습니다.

import sys

src = sys.argv[1]
dst = sys.argv[2]



f = open(src)
tab_content = f.read()
f.close()


space_content = tab_content.replace("\t", " "*4)

f = open(dst,'w')
f.write(space_content)
f.close()


위 스크립트를 통해 dos창에서 원본 txt파일을 불러오고, tab을 4개의 space로 바꾼 후 다른 txt로 저장할 수 있습니다.

2017/07/17 21:35

Bigfrog

package java_tutorial;

import java.util.Scanner;

public class ReplaceTab {
    public static void main(String[] args) {     
        Scanner obj=new Scanner(System.in);

        System.out.print("Input:");
        String str=obj.nextLine();

        System.out.println("Before:"+str);

        str=str.replaceAll("\t", "    ");
        System.out.println("After:"+str);

        str=str.replaceAll("    ", "\t");
        System.out.println("Final:"+str);
    }

}

2017/07/18 18:15

최원석

[Python 3.6]

import re
def replace4space(inStr):
    lines = inStr.split("\n")
    for line in lines:
        mat = re.match("^\t+", line)
        if mat:
            line = "    "*mat.end() + line[mat.end():]
        print(line)

2017/07/22 14:53

Eliya

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException{
        FileReader reader = new FileReader("input.txt");
        FileWriter writer = new FileWriter("output.txt");

        int ch;

        while((ch = reader.read()) != -1) {
            if(ch == '\t') writer.write("    ");
            else writer.write((char) ch);
        }

        reader.close();
        writer.close();
    }
}

2017/07/29 21:30

곽철이

import sys

src = sys.argv[1]
dst = sys.argv[2]



f = open(src)
tab_content = f.read()
f.close()


space_content = tab_content.replace("\t", " "*4)

f = open(dst,'w')
f.write(space_content)
f.close()

2017/08/06 12:12

Bigfrog

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        String replacedText = null;
        if (input.contains("\t")) {
            replacedText = input.replace("\t", "    ");
        }
        System.out.println(replacedText);
        br.close();
    }
}

2017/08/14 22:10

임주성

word= "a    b   c   d"

result=word.replace("\t","    ")
print(result)

2017/08/21 11:53

iamm00n

JAVA

public class Question_019 {

    public static void main(String[] args) throws IOException {
            FileReader fr = new FileReader("d:\\Person\\study\\workspace\\codingDojang\\src\\codingDojang\\Question_019.java");
            FileWriter fw = new FileWriter("d:\\Person\\study\\workspace\\codingDojang\\src\\codingDojang\\Question_019.txt");
            int data = 0;

            while((data = fr.read()) != -1) {
                if((char)data == 9) {
                    data = (byte)32;
                    for(int i = 0; i < 4; i++) {
                        fw.write(data);
                    }
                } else {
                    fw.write(data);
                }
            }

            fr.close();
            fw.close();
    }

}

2017/08/22 16:25

androot

public class Example19 {
    public static void main(String[] args) {
        String str = "들여쓰기  테스트";

        StringBuilder sb = new StringBuilder();
        sb.append(str.replaceAll("\t", "    "));

        System.out.println(sb.toString());
    }
}

replaceAll 이용해서 간단하게 작성해 보았습니다.

2017/08/29 00:16

흑돼지

import os

def f(dir1):
    for (path, dir, files) in os.walk(dir1):
        for filename in files:
            if filename.split('.')[-1] == 'py':
                f1 = open(os.path.join(path, filename))
                f2 = f1.read().replace('\t','    ')
                f1.close()
                f1 = open(os.path.join(path, filename),'w+')
                f1.write(f2)
                f1.close()

f('D:\\')

2017/08/31 11:33

piko

String tabTospace(String text){ text.replaceAll("\t"," "); return text; }

2017/09/04 00:30

sungeun hong

with open('name.in') as fin:    #파일을 연다
    while True:
        rline=fin.readline()    #읽는다
        if not rline : break    #만일 읽은게 없으면 파일 끝으로 간주하고 탈주
        if rline[0] == '\t' : rline='    '+rline[1:]    #첫 문자가 탭이면 4공백으로 교환
        print rline    #출력

2017/09/11 14:51

Juhee Lee

def asdf(sourcecode):
    return sourcecode.replace("\t"," "*4)

2017/09/22 15:47

고든

public class tab_to_space {
    public static void main(String[] args) {
           String str="aaa\taaa\taaa";
            System.out.println(str);


            str=str.replaceAll("\t","    ");
            System.out.println(str);
    }
}

2017/09/27 09:20

김문수

package codingdojang;

public class ex19 {

public static String change(String a) {
    String b = a.replaceAll("\t"," ");
    return b;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String a = "a   b   c   d";
    System.out.println(change(a));
}

}

2017/09/29 11:32

이병호

f = open("c:/file.txt", "r")
d = f.read()
f.close()
n = d.replace("\t","    ")
nf = open("c:/newfile.txt", "w")
nf.write(n)
nf.close

2017/10/03 21:20

bat

맞는지 정확히 확인을 못함;; - bat, 2017/10/03 21:20
def transformation(filename, newname):   #전자는 기존 파일, 후자는 새로 쓸 파일이름
    a = open(filename, 'r').read()       # 문자열로 만듦
    a = a.replace('\t', ' ' * 4)
    with open(newname, 'w') as f:
        f.write(a)



2017/10/21 21:31

李愼言(이신언)

f = open('file.txt',w)

for lin in f.readlines(): line = line.replace('\t',' ')

2017/10/30 22:00

Oh Suhyeon

var str = 'String tap\thi .';

str = str.replace(/\t/g,"    ");
console.log(str);

2017/11/08 20:25

이우진

int main()
{
    char str[] = { "abcd\ttefgh\tijkl\n" };
    int i;

    printf("%s", str);

    for (i = 0; i < sizeof(str) / sizeof(char); i++);
    {
        if (str[i] == '\t')
        {
            str[i] = '    ';
        }
    }
    printf("%s \n", str);
    getchar();
    return 0;
}

}

2017/11/14 19:49

junpil lee

def Tab_to_Space(Centense): Centense.replace("\t"," ") print(Centense)

Tab_to_Space("adwfhhadshf\tddafdijsl")

2017/11/16 13:54

김남혁

txt에 한줄 만들어서 확인했을땐 작동은 했습니다..

code1 = open('파일경로\파일이름','r')
data1 = code1.read()
data2 = data1.replace('\t','    ')
code2 = open('파일경로\파일이름2','w')
code2.write(data2)
code2.close()

2017/11/21 19:18

장동영

import sys

inf = open(sys.argv[1], 'r')
tem = inf.read()
inf.close()

inf = open(sys.argv[1], 'w')
inf.write(tem.replace("\t"," "*4))
inf.close()

2017/11/24 22:45

nabina

f = open('Tab_to_Space4_1.txt','r')
h = open('Tab_to_Space4_2.txt','w')
a=f.read().replace('    ','    ')
h.write(a)
h.close()
f.close()

2017/11/27 22:52

Ryan

fin=open("test.txt",'r')
fout=open("test2.txt",'w')

allline = fin.read()
allline2 = allline.replace("\t"," "*4)
fout.write(allline2)

fin.close()
fout.close()

2017/12/02 01:26

영이

code = "    ekfkw  ekfk wkkslfalse"
code.replace('\t', ''*4)
print(code)

2017/12/03 02:17

홍철현

public class Tab {
    public static void main(String[] args) {     
        Scanner obj=new Scanner(System.in);

        System.out.print("Input:");
        String str=obj.nextLine();

        System.out.println("Before:"+str);

        str=str.replaceAll("\t", "    ");
        System.out.println("After:"+str);

        str=str.replaceAll("    ", "\t");
        System.out.println("Final:"+str);
    }

}







2017/12/05 13:15

떼디

after = before.replace("\t", " " * 4)

with open('after.txt', 'w') as f:
    f.write(after)

2017/12/09 13:45

욱이

  • 파일 이름을 입력받아 현재폴더부터 하위폴더를 검색하여 동일한 이름의 파일을 찾아 해당 파일의 "tab" 문자를 "공백문자 4개"로 변환하여 새로운 파일을 생성 및 저장하는 프로그램입니다.
  • 텍스트 형태의 파일에서 정상 작동하나 그 외의 파일에서는 작동하지 않을 수 있습니다.
  • 소스파일은 프로그램을 실행하는 폴더 및 그 하위폴더에 있어야 합니다.
  • 입력한 파일을 찾지 못한 경우에는 변환작업 없이 프로세스가 끝납니다.
import os

print("<<< Convert tab to 4 spaces>>>","\n")

srfile = input("Enter the file name(usage : name.ext):") # 소스파일 이름을 입력받음
dir = os.getcwd()                                        # 프로그램을 실행하는 현재폴더 위치를 리턴받음

def search(dir):
    filenames = os.listdir(dir)                          # 현재폴더의 파일 또는 디렉토리 이름들을 리스트로 리턴받음

    for filename in filenames:
        full_filename = os.path.join(dir, filename)      # 현재폴더와 파일명(또는 디렉토리)이름을 결합하여 리턴받음

        if os.path.isdir(full_filename):                 # 결합하여 리턴받은 값이 디렉토리이면
            search(full_filename)                        # 디렉토리이면 해당 디렉토리의 파일 또는 디렉토리 이름들을 리스트로 리턴받음(하위폴더 검색)

        if filename == srfile:

            f = open(full_filename, 'r')
            source = f.read()                            # 파일의 내용을 읽어들여
            converted = source.replace("\t"," "*4)       # 'tab' 문자를 '공백 4개'로 변환한 내용을  coverted 객체로 리턴함
            f.close()

            f = open("new_"+srfile, 'w')                 # 변환된 내용을 저장할 새로운 파일을 열고
            f.write(converted)                           # converted 객체의 변환된 내용을 새로운 파일에 저장함
            f.close()

            print("\n")
            print("Process complete!")
            print("'%s' file created." % ("new_"+srfile))
            input(" ")
            break                                        #프로세스를 종료함

search(dir)

2017/12/11 19:39

justbegin

tmp=''
with open('test', 'r') as fr:
    for line in fr:
        line=line.replace('\t',' '*4)
        tmp+=line
with open('test', 'w') as fw:
    print(tmp, file=fw)

test파일 내용은

            tab3
        tab2
    tab1
tab0

입니다.

2017/12/11 22:04

빗나감

#!/usr/bin/python

import getopt
import sys
import os

def check(path):
    if path == "False":
        print("The directory does not exist in the path.")
    else:
        print("A directory exists in the path.")

def rep_line(get_line):
    rep_line=get_line.replace('\t', ' *  ')
    return(rep_line)

def print_help():
    return ("""
    Please enter the following options
    ==================================

    -r: Convert tabs to 4 spaces.
    Please enter a Text filename to convert.
    ==================================

    -h: View the help message again.
    """)

def main():
    try:
        opts, args=getopt.getopt(sys.argv[1:], "r:")
    except getopt.GetoptError as err:
        print str(err)
        sys.exit(1)

    for opt, arg in opts:
        if opt == "-r":
            path=(sys.argv[2])
            check(path)
            file=open(path, 'r')
            for line in file.readlines():
                result=rep_line(line)
                print result
                wfile=open(path+'.new', 'a')
                wfile.write(result)

        elif opt == "-h":
            print_help()

if __name__ == '__main__':
    main()

2017/12/13 16:52

윤병호

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class Main {

    public static void main(String[] args) throws Exception {
        //파일을 입출력
        BufferedReader br = new BufferedReader(new FileReader("C:/Users/Lee/Documents/tab.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("C:/Users/Lee/Documents/output.txt"));

        //파일 내용을 제일 윗줄 부터 한줄씩 읽어서 마지막 까지 loop
        while (true) {
            //파일에 내용을 한줄씩 String에 저장
            String line = br.readLine();
            //파일에 끝에 도달하면 loop 종료
            if (line == null)
                break;
            //String 안에 탭문자(\t)를 "    "으로 변환
            line = line.replaceAll("\t", "    ");
            //출력 시킬 파일에 기록
            bw.write(line);
            //개행 문자 삽입
            bw.newLine();
        }
        //사용한 파일입출력 종료
        br.close();
        bw.close();
    }
}

2017/12/20 14:26

이장흠

li = 'hi    hello \n    hi hello\n  hi'
li = list(li)
find =['32','32','32','32']
lis=[]
liss=[]
x = 0
y = 1
for i in li:
    l = ord(i)
    lis.append(l)
for _ in lis:
    if lis[x] == 10:
        x = x+1
        if lis[x] == 9:
            lis[x] = find
            continue
    x = x + 1

print(lis)

basestring = (str,bytes)
test =''
ping =[]
ping2 =[]
def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring): 
            #스트링형이 아닌 이터러블의 경우 - 재귀한 후, extend
            result.extend(flatten(el)) #재귀 호출
        else:
            #이터러블이 아니거나 스트링인 경우 - 그냥 append
            result.append(el)
    return result

lis = flatten(lis)
for i in lis:
    test = int(i)
    ping.append(test)
for i in ping:
    test = chr(i)
    ping2.append(test)
print(ping2)
s = ''.join(ping2)
print(s)



숫자로 변환해서 교체하고 다시 문자로 변환

2017/12/20 18:45

완전초보

public class tab_to_space {


    public static void main(String[] args) {
        String sampleString = "tabsldfjlrwTabsdflkjsfdlfTabsldkjf";

        System.out.println("이전"+sampleString);
        sampleString = sampleString.replaceAll("Tab", "    ");

        System.out.println("결과 : "+sampleString);
    }
}

문자 Tab 이라길래 \t을 칠수 없는 상황이 문제인건가 했는데 다른 분들 소스 보니 아닌가보네요 Tab->\t로 바꾸면 될 듯 합니다.

2017/12/22 10:45

김준학

filename = input("파일 이름을 입력하십시오: ")
with open(filename, "r") as f:
    Text = f.readlines()
    for i in range(len(Text)):
        exchangedText= Text[i].replace("/t","    ")
    with open(filename+"_exchanged", "w") as h:
        h.write(exchangedText)

2017/12/24 02:49

박지상

import java.util.Scanner;

public class tab {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String space = line.replaceAll("\t", "    ");
        System.out.println(space);
    }
}

2017/12/28 15:25

안지혜

text = "\tabcd"
#import re
#re.sub("\t","\n\n\n\n",text)
text.replace('\t','\n\n\n\n')

2017/12/28 15:54

얏홍

    public static String tabSpaceChange(String text){
        text.replaceAll("\t", " ");
        return text;
    }

2018/01/01 18:34

Shim Jinbo

import sys

Init = sys.argv[1]

f = open(Init, 'r')
tab = f.read()
space = tab.replace('\t', '    ')

with open(Init, 'w') as g:
    g.write(space)

이렇게 해봤더니 문제점: 한글이 깨집니다. 글자인코딩에 대해서는 잘 몰라서 해결은 못했습니다...

2018/01/02 01:08

HS

파이썬 입니다.

def to4space(src):
    result=""
    result=src.replace('\t','    ')
    return result
print(to4space('''
sum=0
for i in range(1,1000):
    if i%3==0 or i%5==0:
        sum=sum+i
    else:
        continue
print(sum)
'''))

2018/01/02 17:30

Ilhoon Kang

#renderer.py
import sys
original = sys.argv[1]
edited = sys.argv[2]
f = open(original)
tab_content=f.read()
f.close()
space_content = tab_content.replace("\t"," "*4)
print(space_content)

실행 시 ..../render.py a.txt b.txt

2018/01/11 14:53

장창원

code = 'this sentence has\ttab in the middle.'
print(code)
def tab2space(code):
    code_split = code.split('\t')
    code_join = '    '.join(code_split)
    return code_join

print(tab2space(code))

2018/01/16 14:13

Jaejun Yoo

a = input('입력하세요. : ')
a = a.replace('\t', '    ')
print(a)

2018/01/19 23:13

whmj

#include <stdio.h>

int main(void){

 int i;
 char testch[] = "this\tis the\ttest sentence!";
 printf("[%s]\n", testch); 

 for(i=0;i<sizeof(testch);i++){

   if(testch[i]=='\t'){
        testch[i]=' ';
   }

  }
    printf("[%s]\n", testch);
    return 0;

}

2018/01/21 15:19

김엽기

자바입니다

public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        List<String> list = new ArrayList<String>();

        while(true) {
            System.out.print("코드(종료시 입력하지 않고 Enter) = ");
            String read = cin.nextLine();
            if(read.length() == 0) {
                for(String str : list) {
                    System.out.println(str);
                }
                break;
            }else {
                list.add(replace(read));
            }
        }

        cin.close();
    }
    public static String replace(String data) {
        return data.replaceAll("\t", "    ");
    }

2018/01/21 16:03

YEAHx4

import sys

tab = sys.argv[1]
space = sys.argv[2]

f = open(tab)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open(space, 'w')
f.write(space_content)
f.close()

2018/01/25 14:33

chann

filename = input("파일 이름 입력: ")

readfile = open(filename, 'r')

writefile = open('outfile.txt', 'w')
contents = readfile.read()
replaced_contents = contents.replace('\t', '    ')
writefile.write(replaced_contents)

readfile.close()
writefile.close()

2018/01/28 23:40

Miazra

        static void Main(string[] args)
        {
            Console.Write("TAB을 포함한 소스코드 입력:");
            string strTabCode = Console.ReadLine();
            Console.WriteLine(strTabCode.Replace("\t", "    "));
        }

2018/01/31 23:50

정태식

Source_code = input ("소스코드를 입력하세요:")
if '\t' in Source_code:
    '\t' == '    '
print (Source_code)

2018/02/01 16:02

백형식

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open(dst, 'w')
f.write(space_content)
f.close()

2018/02/03 15:33

김동하

filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()

2018/02/03 20:17

박시현

# 파이썬
# tab_to_space.py
# command line: python tab_to_space.py space_file.txt tab_file.txt

import sys

a1 = sys.argv[1]
a2 = sys.argv[2]

f = open(a1)
tabs = f.read()
f.close()

spaces = tabs.replace("/t", " "*4)

f = open(a2, 'w')
f.write(spaces)
f.close

2018/02/05 16:08

olclocr

import re

sourcecode = '''A씨가 납품하려는  소스코드
    sdasdasdw
    asdasdasd
asdsdsd'''
p = re.compile('^\t', re.MULTILINE)
sourcecode = p.sub(' '*4, sourcecode)

sourcecode

2018/02/06 11:50

김용준

java 8

    String input  = "abc    bbb ddd";
    String result = "";

    for(int i=0; i<input.length(); i++) {

        char ch = input.charAt(i);

        if(ch == '\t') {
            result = result + "    ";
        }else {
            result = result + Character.toString(ch);   
        }

    }

    System.out.println("result >> " + result);

2018/02/07 14:45

운이v

file_path=input("변경하고자 하는 파일의 경로를 입력하시오.ex)\"C:\Python\\test.txt\"\n")

f=open(file_path,'r')
content=f.read()
changed_content=content.replace('\t',' '*2)
f.close()

f=open(r"C:\Users\BOOKER\result.txt",'w')
f.write(changed_content)
f.close

2018/02/15 02:41

D B

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream in;
    ofstream out;
    string tmp;

    in.open("Original.txt");
    out.open("Fixed.txt");

    while (!in.eof())
    {
        getline(in, tmp);
        if (tmp[0] == '\t')
        {
            tmp.erase(0, 1);
            tmp.insert(0, "    ");
        }
        out << tmp << endl;
        tmp.clear();
    }

    in.close();
    out.close();

    return 0;
}

2018/02/19 21:01

이승헌

txt파일을 읽어서 변환하고 저장하는 프로그램입니다! 자바입니다!

package CodingDojang;
import java.util.regex.*;
import java.util.*;
import java.io.*;

class TabConverter {

    private static String tabConverter(String _input) {
        String output;

        output = _input.replaceAll("\t", "    ");

        return output;
    }

    public static void main(String[] args) {
        String temp;
        File readFile = new File("C:\\Users\\sangw\\Desktop\\상우\\프로그래밍\\코딩도장", "test.txt");
        File writeFile = new File("C:\\Users\\sangw\\Desktop\\상우\\프로그래밍\\코딩도장", "testConverted.txt");

        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            br = new BufferedReader(new FileReader(readFile));
            bw = new BufferedWriter(new FileWriter(writeFile));
            String line;
            while ((line = br.readLine()) != null) {
                temp = tabConverter(line);
                bw.write(temp);
                bw.newLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br != null && br != null) try {br.close(); bw.close();} catch (IOException e) {}
        }
    }
}

2018/02/27 13:38

sangw0804

import os
# 1-1파일 위치와 확장자 입력 받기
filepath = input("파일경로를 입력하세요: ")
ext = input("확장자를 입력하세요: ")
'''
2 파일 전체경로 리스트로 받기
파일경로와 확장자를 파라메터로 받아서 하위디렉토리 모두 탐색해서 조건에
맞는 파일전체경로를 list 에 담아 리턴한다.'''

# 1-2 함수: 변수 - 파일 경로, 확장자를 받으면 - 파일경로를 리스트로 저장
def getfilelist(filepath, ext):
    filelist = []
    for path, dir, files in os.walk(filepath):
        for filemn in files:
            if (filemn.lower()).endswith(ext.lower()):
                filelist.append(path + "\\" + filemn)
    return filelist
# 2-1  :파일경로 및 확장자를 받아서 출력, 백업파일 생성 (copy 경로 파일경로.bak)
for _path in getfilelist(filepath,ext):
    print(_path)
    os.system("copy %s %s" % (_path, _path + ".bak"))
# 2-2  : 백업파일을 열고 읽은다음, 새로운 변수에 저장, replace 하기
    with open(_path + ".bak", 'r') as f:
        srcContent = f.read()
        with open(_path, 'w') as tempo:
            tempo.write(srcContent.replace("\t","    "))

무명소졸님의 코드를 보고 공부했습니다.

2018/03/03 17:45

yonggyu park

package Q1;

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;

public class Q19 { public static void main(String[] args) { File inFile = new File("C:\Users\Public", "in.txt"); File outFile = new File("C:\Users\Public", "out.txt"); String before,stop=""; try { BufferedReader br = new BufferedReader(new FileReader(inFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));

        while ((before = br.readLine()) != null) {
            System.out.println(before);
            stop = before.replace("\t", "    ");
            bw.write(stop);
            bw.newLine();
          }
            bw.flush();
            br.close();
    }catch(IOException e) {
        e.printStackTrace();
    }

}

}

2018/03/06 16:57

김원응

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PracticeWW
{
    class Replace
    {
        public string Change()
        {
            string nameChange = name.Replace("\t", "    ");
            return nameChange;
        }

        public static string name = "\t홍\t길\t동";

    }

    class Program
    {
        static void Main(string[] args)
        {
            Replace replace = new Replace();
            Console.WriteLine(Replace.name);
            Console.WriteLine(replace.Change());
        }
    }
}

C#입니다

2018/03/12 11:48

정관영

Of = input("ENTER FILE NAME: ")
Of= open(Of)
data = Of.read()
data = data.replace('\t','    ')
Nf = open("Newfile.txt",'w')
Nf.write(data)
Of.close()
Nf.close()

2018/03/13 12:02

DEMIAN

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TabReplace {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String filePath = "C:\\Users\\present\\Desktop\\test\\1234.txt";
        String filePath2 = "C:\\Users\\present\\Desktop\\test\\12343.txt";
        try {
            FileReader fis = new FileReader(new File(filePath));
            FileWriter fos = new FileWriter(new File(filePath2));

            int i=0;

            while((i=fis.read()) != -1){

                if(i == '   '){             
                    fos.write(' ');
                    fos.write(' ');
                    fos.write(' ');
                    fos.write(' ');
                }else{
                    fos.write(i);
                }
            }
            fos.flush();
            fis.close();
            fos.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

2018/03/16 22:14

김태훈

file_name=input("Enter the file name :" ) fp = open("D:/{}".format(file_name,'w')) data = fp.read() date = data.replace("\t"," ") nfp = open("D:/new_{}".format(file_name),'w') nfp.write(data) fp.close() nfp.close()

2018/03/19 14:53

yijeong

import sys

fname = input("input file name :")
f = open(fname, "r")
line = f.read()

trans = line.replace("\t", "    ")
f = open(fname, "w")
f.write(trans)
f.close()



2018/03/20 17:15

bnewkk

python 3.6.1

filename = input("Enter the file location and name:")
file = open(filename, 'r')
file_correction = file.read().replace('\t', '    ')
fout = open(filename, 'w')
fout.write(file_correction)
file.close()

2018/03/24 16:05

최상혁

    public static String tabTo4Space(String iStr) {
        String oStr = "";
        char[] charArr = iStr.toCharArray();
        for(int i = 0; i < charArr.length; i++) {
            if(charArr[i] == '\t') oStr += "    ";
            else oStr += charArr[i];
        }
        return oStr;
    }

2018/03/26 16:35

이준석

imports:

import (
    "os"
    "strings"
)

function:

func Tab2Spaces(filename string) {
    ifile, _ := os.Open(filename)
    defer ifile.Close()

    stat, _ := ifile.Stat()
    bs := make([]byte, stat.Size())
    ifile.Read(bs)
    str := string(bs)
    newstr := strings.Replace(str, "\t", "    ", -1)

    ofile, _ := os.Create(filename + "-tab2spaced.txt")
    defer ofile.Close()
    ofile.WriteString(newstr)
}

2018/03/27 13:57

mohenjo

import sys

src = sys.argv[1] dst = sys.argv[2]

f = open(src, 'r') tap_read = f.read() f.close()

space_contents = tap_read.replace('\t', ' '*4) f = open(dst, 'w') f.write(space_contents) f.close()

2018/04/02 11:08

정광호

source = input()
f = open(source, 'r')
a = f.read()
p = a.replace("\t", "    ")
f.close()
f = open(source, 'w')
f.write(p)
f.close()

2018/04/02 14:48

최성범

package prob_01;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FindContent {

    private static BufferedReader f_Reader;
    private static BufferedWriter f_Writer;

    public static void main(String[] args) throws IOException {
        f_Reader = new BufferedReader(new FileReader("input.txt"));
        f_Writer = new BufferedWriter(new FileWriter("output.txt"));

        while(true) {
            String i_dataLine = f_Reader.readLine();
            StringBuffer o_data = new StringBuffer();

            if(i_dataLine==null)
                break;

            for(int i=0; i<i_dataLine.length(); i++) {
                if(i_dataLine.charAt(i)=='\t') {
                    o_data.append("    ");
                }
                else {
                    o_data.append(i_dataLine.charAt(i));
                }
            }

            f_Writer.write(o_data.substring(0, o_data.length()));
            f_Writer.newLine();
        }

        f_Reader.close();
        f_Writer.close();
    }
}

2018/04/09 22:45

이호영


2018/04/10 13:51

조범연

s = " dlafkalfkalf aldkalfalfkalkflaf aflafkalf" \ "aflaflafla aflafkalfka"

print(s.replace('\t',' '))```{.python}

```

2018/04/12 18:26

구안토

# python3
with open('test.txt','r') as f: r = f.read()
with open('test.txt','w') as f: f.write(r.replace('\t',' '*4))

2018/04/13 18:42

김태영

import java.util.Scanner;

public class Tab {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();
        str.replaceAll("\t", "    ");

        System.out.println(str);
    }
}

2018/04/15 12:05

聂金鹏

#include <iostream>
using namespace std;

int main(void)
{
    char cText[] = "Hello\tWorld";

    cout << "바꾸기 전 문장:" << cText << endl;

    cout << "변경 후 문장: ";
    for (int i = 0; i < sizeof(cText); i++)
    {
        if (cText[i] == '\t')
            cout << ' ';
        else
            cout << cText[i];
    }
    cout << endl;
}

2018/04/26 21:30

태역

Python 2.7

def changetabs(sourceCode):
    result  = str()
    with open(sourceCode, 'r') as f:
        lines = f.readlines()
        for line in lines:
            if line.startwith('\t'):
                result += line.expandtabs(4)
            else:
                result += line
    with open(sourceCode, 'w') as f:
        f.write(result)

2018/05/01 22:28

오준균

i1 = input("소스 코드 위치를 입력하세요: ") file = open(i1,'r') contents = file.readlines() for line in contents: line = line.replace('\t',' ') file.close() file = open(i1,'w') file.write(contents)

2018/05/05 01:05

최우성

// 자바입니다
   public static void main(String[] args) {
        String str="aaa\taaa\taaa";
        str=str.replaceAll("\t","    ");
        System.out.println(str);
    }
// 스트링 메서드 좋은 게 많네요

2018/05/05 10:57

정몽준

python

def tab_to_space(file):
    return file.replace("\t","    ")

2018/05/08 18:17

관관

자바 내장함수 replaceAll 사용했습니다.
public class T {
    public static void main(String[] args) {
        String str="aaa\taaa\taaa";
        System.out.println(str);


        str=str.replaceAll("\t","    ");
        System.out.println(str);


    }

}

2018/05/14 15:44

배혁남

/*
탭을 공백 문자로 바꾸기
A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 개발된 소스코드들은 탭으로 들여쓰기가 된것, 
공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.

문제
A씨를 도와줄 수 있도록 소스코드 내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.

 */
package codingTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReTaWithSpCh {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);                                      //  텍스트 파일 읽어오는 스캐너
        String fileroute = "./src/codingTest/Text/replaceAllTest.txt";              //  소스파일 텍스트로 복사해서 소스 수정
        String text;
        boolean flag = true;                                                        //  불분명문자 판별 플래그
        try {
            scan = new Scanner(new File(fileroute));
            while(scan.hasNextLine()) { 
                if(flag) { text = scan.nextLine().substring(1); flag = false; }     //  윈도우에서 쓴 글이므로 첫줄 가장첫문자에 불명문자 빼고 가져옴.
                else { text = scan.nextLine();  flag = true; }  
                System.out.println(text + " <- 바꾸기전 문자열(소스)");
            }
            System.out.println("");

            scan = new Scanner(new File(fileroute));
            while(scan.hasNextLine()) {                                             //  읽어올 줄 있나판별
                if(flag) { text = scan.nextLine().substring(1); flag = false; }
                else { text = scan.nextLine(); }            
                text = text.replaceAll("\t", "    ");
                System.out.println( text + " <- 바꾼 후 문자열(소스)");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

2018/05/18 16:33

이병덕

def fileTap2Space(fname):
    with open(fname, 'r', encoding="UTF8") as f:
        data = f.read()
        data = data.replace("\t", " " * 4)
    with open(fname, 'w', encoding="UTF8") as f:
        f.write(data)
    return data

#print(fileTap2Space('1. Multiples of 3 and 5.py'))

import os

#_dir = input("_dir: ")
#ext = input("ext: ")

_dir = 'C:\\Users\\Administrator\\PycharmProjects'
ext = '.py'
for root, dirs, files in os.walk(_dir):
    for file in files:
        if file.endswith(ext):
            print(fileTap2Space(root + '\\' + file))

2018/05/19 15:14

재즐보프

public class TabToSpace {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sentence = "hi \t\t\t\t\tt\t\t my name is jun";
        System.out.println(sentence);


        System.out.println(sentence.replace("\t", "    "));
    }

}

2018/05/22 18:11

임명준

#! Python
import os

def encodingFile(fileName):
    f = open(fileName, 'r')
    fi = open(fileName, 'w')
    for data in f.read():
        data.replace("\t", " "*4)
        fi.write(data)
    f.close()
    fi.close()


encodingFile("test.py")

2018/05/26 23:01

meteor

Python 3

f = open(filename, 'r')
data = f.read()
data = data.replace("\t", "    ")
f_new = open(filename_new, 'w')
f_new.write(data)
f_new.close()
f.close()

2018/05/28 12:56

Gerrad kim

fr = open("test", 'r')
fw = open("test2", 'w')
while True:
    line = fr.readline()
    if not line:
        break;
    for i in range(0, len(line)):
        if line[i] == '\t':
            fw.write(' ' * 5)
        else :
            fw.write(line[i])


fr.close()
fw.close()

2018/05/28 16:38

태준김

text = open("souce.txt","r").read()

change_tab = text.replace("\t","    ")
print(change_tab)

2018/05/29 02:26

조성은

with open('SourceCode.txt', 'r') as f:
    new = (f.read()).replace('\t', '    ')

with open('SourceCode.txt', 'w') as f:
    f.write(new)

2018/06/10 20:16

박유빈

static void Main(string[] args) { string Text = File.ReadAllText(@"E:\TebTest.txt"); Text = Text.Replace('\t', ' '); Text = Text.Replace(" ", " ");

        Console.WriteLine(Text);
    }

2018/06/11 15:10

我是谁(是不是很神奇?)

import sys, os
f = open( sys.argv[1], 'r' )
t0 = f.read()
f.close()

f = open( sys.argv[1], 'w' )
f.write( t0.replace( '\t', ' ' * 4 ) )
f.close()

os.system( 'cat ' + sys.argv[1] )

한번따라해봤는데 재밌네요

2018/06/11 19:37

leak

def tapToSpace(data):
    return data.replace('\t', ' '*4)

2018/06/12 23:14

harumaru

def solution():
    f = open("test.txt","r")
    code = f.read()

    print(code.replace("\n\t", "    "))

    f.close()

2018/06/17 22:11

Jace Alan

f = open('test.txt','r')
s = f.read().replace('\t','    ')

f.close()

f = open('test.txt','w')

f.write(s)
f.close()


쌩초보. 눈에 거슬리는거 있으면 지적좀. 없겠지만....

2018/06/23 16:42

나윤형

들여쓰기의 탭만 수정되게 하였습니다. 탭과 공백4개만을 들여쓰기로 판단합니다

text = "\t    \tsource\tcode    exam\tple\n"

def tabconv(text):
    textsplit = text.split('\t')
    i = 0
    for t in textsplit:             # 들여쓰기 카운트
        if t == '' or t == '    ': i += 1
        else : break

    j = 0
    result = ''
    for t in textsplit:
        if j < i:                   # 들여쓰기
            result = result+t+'    '
        elif j == len(textsplit)-1: # 문자열 마지막 부분
            result = result+t
        else:                       # 문자열
            result = result+t+'\t'
        j = j+1
    return result

with open('d:/temp/ex.txt','w',encoding='utf8') as f:
    print('원본: '+text,file=f,end='')
    print('수정: '+tabconv(text),file=f,end='')

2018/06/24 08:28

Creator

package com.company;

import java.io.*;

public class Changetext {
    public static void fileReader(String filename) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(filename));
        BufferedWriter wr = new BufferedWriter(new FileWriter("test1.txt"));
        String line;
        try {
            while ((line = br.readLine()) != null) {
                String li = line.replaceAll("\t", "    ");
                wr.append(li + "\r\n");
                System.out.println(line.equals(li));
            }
        }
        catch (FileNotFoundException e){
            System.err.println("파일이없습니다");
        }
        catch (IOException e){
            System.err.println("무슨이유로 처리할수없습니다.");
        }
        finally {
            br.close();
            wr.close();
        }
    }
}
public class Main {

    public static void main(String[] args) throws IOException {
        Changetext.fileReader("test.txt");
    }
}

2018/07/02 18:21

이동수

with open('C:\\Park\\file.txt','r') as file:
    text=file.read()
    replaced_text=text.replace('\t','    ')

with open('C:\\Park\\replaced_file.txt','w') as replaced_file:
    replaced_file.write(replaced_text)

2018/07/02 23:38

박태규

with open('tabs.txt', 'r', encoding='UTF-8') as f:
    print(f.read().replace('\t', ' ' * 4))

2018/07/03 14:55

홍길동

package kennsyu_イスンウ_個人練習;

public class cd_0003 {

    public static String tapTo4Space(String source) {
        String convertSource = source.replace("\t", "    ");
        return convertSource;
    }

}

2018/07/06 10:12

LeeSeungwoo

replace("\t", "    ")

2018/07/07 21:27

Park Seok Eun

fname = input("파일 이름을 입력하세요. : ")
try:
    f=open(fname,'r')
except:
    print("파일 이름을 잘못입력하셨습니다. 프로그램을 종료합니다.")
    quit()

flines=f.read()
f.close()
flines=flines.replace("\t",' '*4)
f1=open("tab_ex2.txt",'w')
f1.write(flines)
f1.close()

2018/07/10 14:50

Jungmin Lee

filename = input("Enter your filename: ")
f = open(filename)
print("".join(f.readlines()).replace("\t","    "))
f.close()

2018/07/24 18:48

김준영

sourcecode = input()
changedsource = sourcecode.replace("/t"," "*4)
print(changedsource)

2018/07/27 03:46

이지연

def fileTap2Space(fname): with open(fname, 'r', encoding="UTF8") as f: data = f.read() data.replac('\t', 'space') with open(fname, 'w', encoding="UTF8") as f: f.write(data) return data

_dir = input("_dir: ")

ext = input("ext: ")

_dir = 'C:\Users\This PC\CodingDojang' ext = '.py' for root, dirs, files in os.walk(_dir): for file in files: if file.endswith(ext): print(fileTap2Space(root + '\' + file))

2018/08/06 19:35

B.stone

def Tab_replace(Text):
    print(Text.replace('\t','    '))

data=input('문자입력: ')
Tab_replace(data)

2018/08/08 14:44

S.H

using System;
using System.IO;

namespace CD019
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string filename = @"c:\temp\source.txt";
                string convString = TAB2SPACE(File.ReadAllText(filename));
                File.WriteAllText(filename + ".converted.txt", convString);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }
        }

        static string TAB2SPACE(string aString) => aString.Replace("\t", "    ");
    }
}

2018/08/21 17:31

mohenjo

# python
a = input('소스코드를 입력해주세요:')
a = a.replace("\t", "    ")

print(a)

2018/08/23 14:34

Da Som kwon

private static String tap(String str) {
        return str.replaceAll("\t", "    ");
    }

2018/08/26 16:29

김지훈

b=input('파일 이름을 입력하시오:')
f=open(b)
a=f.read()
c=a.replace('n','    ')
f=open(b,'w')
f.write(c)
f.close()

2018/08/26 21:43

전형진

str1 = raw_input("input file : ")

f = open(str1,'r')

text=f.read()

print(text)

text2=text.replace("\t"," "*4)

f.close()

2018/09/01 12:13

오왕씨

var myFindChangeFile = File.openDialog('File Select');

var Finddoc = myFindChangeFile.open();

var str = Finddoc.read();

Finddoc.close();

var myResult = str.replace (/\t/g, '');

myFindChangeFile.open('w');

myFindChangeFile.write(myResult);

myFindChangeFile.close();

2018/09/06 12:58

jey0109

filename = input("파일의 이름을 입력하세요 : ") file = open(filename) file = file.read() refile = file.replace("\t", " ") file = open(filename, 'w') file.write(refile) file.close()

2018/09/07 00:53

문승현

f = open("test.txt", 'r')
strVal = f.read()
strVal.replace("\t", "    ")
f.close()

f = open("test.txt", 'w')
f.write(strVal)
f.close()

2018/09/07 16:21

셈우

// =====================================
private static String tapToSpace(String st) {
        return st.replaceAll("  ", "    ");
    }

2018/09/10 18:46

채규빈

str="111\t2222"
print(str)
str = str.replace("\t","    ")
print(str)

2018/09/12 17:27

강창열

def tab_to_space(a):
    return a.replace("\t","    ")

2018/09/19 21:45

쨔이

import os

def replace_str(src=''):
    if not src:
        return src
    else:
        result = ''
        for idx, ch in enumerate(src):
            if src[idx] == '\t':
                result = result + '    '
                next_idx = idx + 1
                if next_idx < len(src) and src[next_idx] != '\t':
                    result = result + src[next_idx:]
                    break
            else:
                result = result + src[idx]
        return result

if __name__ == "__main__":
    source = os.path.join(os.getcwd(), 'Replace', 'sample.py')
    target = os.path.join(os.getcwd(), 'Replace', 'sample_new.py')
    with open(source, 'r') as f:
        with open(target, 'w') as f2:
            for i, line in enumerate(f):
                result = replace_str(line)
                print "%3d : %s" %(i, result)
                f2.write(result)
        f2.close()

Replace라는 폴더에 sample.py라는 들여쓰기 부분에 탭이 쓰인 파일을 변경해서 sample_new.py로 저장합니다. replace함수를 쓰지 않았고 들여쓰기 부분만 변경하도록 했습니다.

2018/09/21 02:04

RumbleBang

public static void main(String[] args) {
        StringBuilder str = new StringBuilder();
        str.append("안녕\t안녕");
        for(int i=0;i<str.length();i++) {
            if(str.charAt(i)=='\t') {
                str.insert(i+1,"    ");
                str.deleteCharAt(i);
            }
        }
    }

2018/09/21 09:46

길경완

#탭을 공백 문자로 바꾸기

f = open("cord.txt", 'r') #탭으로 입력된 소스코드 파일 열기
text = f.read()
f.close()

text = text.replace('\t', ' '*4) #탭을 공백으로 바꿔주기

f = open('cord_correct.txt', 'w') #수정된 소스코드 파일 저장
f.write(text)
f.close()


2018/10/03 22:11

달품

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Solv {
    public static void main(String[] args) {
        FileReader fr;
        FileWriter fw;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader("src.txt");
            fw = new FileWriter("out.txt");

            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);

            String line = "";
            while ((line = br.readLine()) != null) {
                fw.write(line.replaceAll("\t", "    ") + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

2018/10/07 05:17

ben

JAVA 사용하여 풀이하습니다. 콘솔로 출력시 결과를 확인할 수 있습니다.

public class TapSpacebar {
    public static void main(String [] args) {
        String str = "abc\tabc\tabc";
        System.out.println(str);

        String result = TapSpacebar.replace(str);
        System.out.println(result);
    }

    public static String replace(String str) {
        String result = str.replaceAll("\t", "    ");

        return result;
    }
}

2018/10/09 17:04

최동철

f = open("tap.txt", "r")

lines = f.readlines()

new_lines = []

for line in lines:
    if line[0] == "\t":
        new_lines.append("    " + line[1:])
    else:
        new_lines.append(line)

f = open("modified_tap.txt", "w")

for line in new_lines:
    #f.write(line + "\n") 저절로 줄바꿈 됨
    f.write(line)

f.close()

2018/10/29 12:57

그사람 남한 볼 수 있어요

include

include

include

char replaceAll(char s, const char olds, const char news);

void main(void){ char s[] = "/t봉숭아 /t학당! 봉숭아 학당! 봉숭아 학당! 봉숭아 학당!"; char *s2;

printf("원본: %s\n", s);

s2 = replaceAll(s, "/t", " ");

// 에러가 있으면 NULL 을 리턴. 에러가 없으면 결과 출력 (s2 != NULL) ? printf("치환: %s\n", s2) : fputs("Replace String Error...\n", stderr); }

char replaceAll(char s, const char olds, const char news) { char result, sr; size_t i, count = 0; size_t oldlen = strlen(olds); if (oldlen < 1) return s; size_t newlen = strlen(news);

if (newlen != oldlen) { for (i = 0; s[i] != '\0';) { if (memcmp(&s[i], olds, oldlen) == 0) {count++; i += oldlen;} else i++; } } else i = strlen(s);

result = (char *) malloc(i + 1 + count * (newlen - oldlen)); //이 부분은 제가 계산을 해봤는데 아마 한글때문에 이렇게계산 하신거 같은데 저도 이부분은 잘 모르겠네요 if (result == NULL) return NULL;

sr = result; // 여기는 동적할당 하고나서 result를 그대로 못써서 다른 포인터 변수에다가 대체 했습니다. 참고하시면됩니당 while (s) { if (memcmp(s, olds, oldlen) == 0) { memcpy(sr, news, newlen); sr += newlen; s += oldlen; } else sr++ = s++; } sr = '\0';

return result; }

replaceAll은 다른분 코드 신데 C로 치환이 어려워서 한번쯤 보시고 습득하시면 좋을듯요

2018/11/02 07:02

김범준

def f2(str):
    result = str.replace('\t','    ')
    return result

2018/11/03 16:33

dodoman

# python 3.7.1

with open(file_path) as f:
    test = f.read()

with open(file_path, 'w') as f:
    f.write("    ".join(test.split("\t")))

2018/11/13 17:19

정지환

public static void main(String[] args) {
        File inputFile = new File("/Users/bellossimo/Downloads/test.txt");
        File outFile = new File("/Users/bellossimo/Downloads/test_out.txt");

        try {
            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
            BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));

            int character = 0;
            while((character = reader.read()) != -1) {
                if(character == 9) {
                    for(int i=0; i<4; i++) {
                        writer.write((char)32);
                    }
                } else {
                    writer.write((char)character);
                }
            }

            writer.close();
            reader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2018/11/24 23:08

김동규

void main()
{
    char str[] = {"\t asdonjawd \t "};
    int i;
    printf("%s\n", str);
    for (i = 0; i < sizeof(str); i++)
    {
        if (str[i] == '\t')
        {
            str[i] = '    ';
        }
    }
    printf("%s", str);
}

2018/12/11 21:58

서규섭

# Tab 문자(\t)를 4개의 공백문자로 바꾸는 소스코드
# source.txt의 내용은 임의로 정해두었다.

f1 = open("C:\doit\source.txt", 'r')
Tab = f1.read()
f1.close()

Space = Tab.replace("\t"," "*4)

f2 = open("C:\doit\source.txt",'w')
f2.write(Space)
f2.close()

2018/12/13 23:09

이찬규

def file_tap2space(fname):
    with open(fname, "r", encoding = "UTF8") as f:
        data = f.read()
        data = data.replace("\t", " "*4)
    with open(fname, "w", encoding = "UTF8") as f:
        f.write(data)
    return data

2018/12/22 22:20

플라토

def replace_(x):
    tap = "\t"
    while True:
        if tap in x:
            x = x.replace("\t","    ")
        else:
            break
    return x

code = "Life\tis\ttoo\tshort"
code1=replace_(code)
print(code1)

2018/12/28 13:20

한울

import sys

f = sys.open("SourceCode.py", "r")
input = list(f.read())
f.close()
f = sys.open("SourceCode.py", "w")
f.write(input.replace("\t", " "))
f.close()


2019/01/02 22:04

Woohyuck Choi

import sys

def change_sentence(sentence):
    sentence.replace('\t', "    ")
    return sentence

txt_file = sys.argv[1]
new_file = sys.argv[2]

f = open(txt_file)
sentences = f.read()
change_sentence(sentences)
n = open(new_file,'w')
n.write(sentences)
f.close()
n.close()

실행은 python code.py file1.txt file2.txt 입니다.

2019/01/03 10:25

C B

```{.python}

```filename = input('') tempfile=open(filename) tempfile=tempfile.read() newfile=tempfile.replace('\t', ' ') tempfile=open(filename, 'w') tempfile.write(newfile) tempfile.close()

2019/01/08 19:58

jj kim

filename=input("파일 이름을 입력해주세요 : ")
tempfile=open(filename)
tempfile=tempfile.read()
tem_str=tempfile.replace("\t","    ")
tempfile=open(filename,'w')
tempfile.write(tem_str)
tempfile.close()

2019/01/09 19:53

박상혁

python 3.7

fn=input('파일 이름: ')
with open(fn) as f:
    with open('(new)'+fn,'w') as nf:
        nf.write(f.read().replace('\t',' '*4))

2019/01/10 12:32

recette

f=open("tab_code.txt")
tab_content=f.read()
f.close()

space_content=tab_content.replace("\t"," "*4)

f=open("tab_code.txt",'w')
f.write(space_content)
f.close()

2019/01/10 23:04

Lapis

public class Solution {
    public String solution(String str) {
        String answer = "";

        answer = str.replace("\t", "    ");

        return answer;
    }
}

모든 \t을 space공백( ) 4칸으로 replace

2019/01/11 12:46

홍준성

def solution(msg):
    answer = ""

    answer = msg.replace("\t", "    ")

    return answer

msg = "이것은\tTab 키를 이용한\t문제이다."

print(solution(msg))

replace를 이용하여 space공백( ) 4칸으로 수정

2019/01/11 12:51

홍준성

text = input()
def tap_to_space(text):
    return text.replace('\t', '    ')

print(tap_to_space(text))

2019/01/14 12:21

D.H.

try:
    f = open("N:/Python/data/project/연습org.txt",'r')
    lines = f.readlines()
    f.close()

    f = open("N:/Python/data/project/연습.txt","w")
    for line in lines:
        f.write(line.replace("\t"," "*4))
    f.close()
except FileNotFoundError:
    print("파일을 찾을 수 없습니다!")
finally:
    pass

2019/01/16 10:57

정재홍

def ChangeTab(string):
    return string.replace("\t", "    ")

print(ChangeTab("Hello\t World!!\t"))

2019/01/17 23:46

얀차

def Tab(st):
    return ''.join('    ' if x == '\t' else x for x in st)

2019/01/20 14:37

김영성

1. 문제

A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.

A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.

2. 풀이

function replaceTapToSpace(str){
  return str.replace(/\t/g, "    ")
}

replaceTapToSpace("이문장뒤에탭을칠거다 탭")

2019/01/21 18:55

돌도끼

stringlist = list(input().split('\t'))
print('   '.join(stringlist))

또는 

liststring = input()
liststring.replace('\t',' '*4)
print(liststring)

또는

stringlist = list(input().split('\t'))
print('    '.join(stringlist))

2019/01/24 18:38

김종율

import re
with open('1.txt', 'r') as rfile, open('2.txt', 'w') as wfile:
    wfile.write(re.sub('\t', ' '*4, rfile.read()))

2019/01/27 19:04

Roy

def chapter01():
    Str = input()
    count = 0
    for i in range(len(Str)):
        if Str[i]=='\t':
            count += 1
    Str = Str.replace("\t", "    ")
    print("Here's correct senctence: ",Str)
    print("Also I can see ", count, "character(s)")
    answer = input('Would you try again?')
    if answer == "Y" or answer == 'y':
        chapter01()
    else:
        return

chapter01()

파이썬 3.7 기준으로 짠 것입니다. 참고로 재귀함수 호출 방식으로 프로그램을 작성해보았습니다.

2019/01/31 00:20

조재현

python

f1=open("filename",'r')
data=f1.read()
rdata=data.replace('\t','    ')
f2=open("filename2",'w')
f2.write(rdata)
f.close()

2019/02/05 12:51

Changmin Mun

def converter(src):  # src: 입력받을 소스코드
    with open(src, 'r') as f:
        body = f.read() # body 변수에 소스코드 본문을 저장
    body_new = body.replace("\t", "    ")
    with open(src, 'w') as f:
        f.write(body_new)
src = input("소스코드 명을 입력해주세요(ex. test.txt): ")
converter(src)

파이썬으로 연습해봤습니다~

2019/02/07 18:38

김기민

input_data=tuple(str(input("소스코드를 입력하세요")))
join_code=[]
for cnt in input_data:
    if cnt =="\t":
        join_code.append('    ')
    else:
        join_code.append(cnt)

print("".join(join_code))

2019/02/13 17:24

이정헌

def tab(contents):
    ans = contents.replace('\t','    ')
    return ans

2019/02/14 00:20

dodoman

with open("source4Tab2Blank.txt","r") as f:
    r = f.read()
    j = r.replace("\t"," "*100) #확인하기 편하게 극단적으로
    print(j)
with open("replace.txt","w") as z: #터미널 확인용
    z.write(j)
with open("replace.txt","r") as z: #터미널 확인용
    g = z.read()
    print("="*35,"절취선","="*35)
    print(g)

2019/02/14 00:30

김규묭

Text = ""

Text = Text.Replace("   ", ' ')
Text = Text.Replace("/t", ' ')

2019/02/14 10:44

동동

public string TabtoSpace(string p_InNum)
        {
            return p_InNum.Replace("\t", "    ");
        }

2019/02/15 11:01

김태진

code = input("code : ")
code.replace("  ", "    ")
print(code)

2019/02/15 13:55

Jeong Sanghyun

 >>> import sys
src=sys.argv[1]
dst=sys.argv[2]

f=open(src)
tab_content=f.read()
f.close()

space_content=tab_content.replace("\t"," "*4)

f=open(dst, 'w')
f.write(space_content)
f.close()

2019/02/16 19:47

이세민

f = open("./source.txt","r") f2 = open("./source2.txt","w") lines = f.readlines() for line in lines: print(line) temp = '' if line[0:1] == ' ': temp = ' ' + temp for l in line: if l == ' ': pass else: temp = temp + l else: temp = line f2.write(temp) f.close() f2.close()

2019/02/17 01:22

임동열

f=open('./source.txt','r')

source = f.read()
f.close()
f=open('./source.txt','w')
f.write(source.replace("\t","    "))
f.close()

2019/02/18 09:08

#디렉터리 탐색
def fileTab2Space(fname):
    with open(fname, 'r', encoding='UTF8') as f:
        data = f.read()
    with open(fname, 'w', encoding='UTF8') as f:
        data = data.replace('\t', ' '*4)
        f.write(data)
    return data

import os
_dir = input("_dir: ") #dir = C:\\Users\\Administrator\\PycharmProjects\\CodingDojang
ext = input("ext: ")
for root, dirs, files in os.walk(_dir):
    for file in files:
        if file.endswith(ext): #확장자 검사
            print(fileTab2Space(root + '\\' + file))

2019/02/20 18:05

정하윤

with open("source4Tab2Blank.txt", 'r') as sourceText :
    originalText = sourceText.read()
print("* 원본 문서 *\n", originalText, "\n")
resultText = ''
for i in originalText :
    if i == "\t" :
        resultText += ' '
    else :
        resultText += i
print("* 수정 문서 *\n", resultText, "\n")

2019/02/21 23:29

좋은나쎔

filename = input('Enter your file name: ')
tempfile = open(filename)
tempfile = tempfile.read()
temp_str = tempfile.replace('\t', '    ')
tempfile = open(filename, 'w')
tempfile.write(temp_str)
tempfile.close()

2019/03/06 23:02

권준형

f=open('test.txt','r') line=f.read() f.close()

t=line.replace('\t',' ')

f.open('test.txt','w') f.write(t) f.close()

2019/03/08 13:59

Fiesta

define _CRT_SECURE_NO_WARNINGS

include

int main() {

char buffer[30];
char result[100] = { 0. };
int len = 0, i = 0, j = 0;

FILE *fp, *fp2;

fp = fopen("hello.txt", "r");
fp2 = fopen("hello2.txt", "w");

fgets(buffer, 30, fp);

while (len < 30) {
    if (buffer[len] == 0)
        break;
    len++;
}

for (i = 0; i < len; i++) {
    if (buffer[i] == '\t')
        buffer[i] = ' ';
}

i = 0;

while (i<len) {
    if (buffer[i] != ' ') {
        result[j] = buffer[i];
        j++; i++;
    }
    else {
        result[j] = buffer[i];
        result[j + 1] = ' ';
        result[j + 2] = ' ';
        result[j + 3] = ' ';
        j += 4; i++;
    }
}

fputs(result, fp2);

fclose(fp);
fclose(fp2);

}

2019/03/10 01:03

황정인

def fileTab2Space(fname):
    f = open(fname, "r", encoding = "UTF-8")
    data = f.read()
    f.close()
    return data.replace("\t", " "*4)

file_name = input("파일 이름을 입력하세요")
replace_data = fileTab2Space(file_name)
print(replace_data)

2019/03/12 12:53

설민혁

Python

import sys

src = sys.argv[1]
dst = sys.argv[2]       #src에서 읽어오고 수정한 내용은 dst에 저장

f=open(src,'r')
tab_content = f.read()
f.close()               #tab이 포함된 텍스트를 tab_content에 저장

new_content = tab_content.replace("\t"," "*4)

f=open(dst,'w')
f.write(new_content)
f.close()




2019/03/14 02:55

챠마

#include <iostream>
using namespace std;

int main()
{
    int sum = 0;
    for (int i = 1; i < 1000; i++) {
        if (i % 3 == 0 || i % 5 == 0)
            sum += i;
    }
    cout << "1000 미만 3과 5의 배수의 합 : " << sum << endl;
    return 0;
}


2019/03/15 19:19

이주원

이승훈님 작성 내용 참고해서 작성해 보았습니다.

파일 이름을 입력 받습니다

file_name = input('enter input file name =') new_file_name = "new_"+ file_name

old_file = open(file_name, 'r') print('old_file:',old_file) # 중간에 확인을 위해 진행하는 값을 출력함

file_content = old_file.readlines() print('file_content:',file_content) # 중간에 확인을 위해 진행하는 값을 출력함

작성할 파일을 엽니다.

new_file = open(new_file_name,'w')

탭을 공백으로 치환합니다.

공백으로 치환하면 탭으로 한것과 구별이 안되어서 의도적으로 ____ 로 변경하였음

for i in file_content: result = i.replace('\t','____') new_file.write(result) old_file.close() new_file.close()

2019/03/19 00:06

문광경

def tab_to_4space(string) :
    return string.replace('\t', '    ')

print(tab_to_4space('\t\t\ttest\tstring\t\t'))

2019/03/22 20:28

SungJin Lee

public class Main {

    public static void main(String[] args) {
        // 탭 키를 4칸뛰우기로 변경하는 코드(4 space)

        String text = "안녕하세요        ";
        text = text.replace("   ", "    ");
        System.out.println(text);
    }

}

2019/03/25 11:54

Cheery Honey

replace_tab_to_space = text.translate({ ord('   '): '    '})

2019/03/25 16:30

박상훈

def transfer(text):
    new_text =""
    for i in text:
        if(i ==("\t")):
            i == " "*4
        new_text+=i

    return text

2019/03/26 01:13

minji choi

f = open("D:/src.py", 'r')

lines = f.readlines()
src = ''

for line in lines:
    src += line

f.close()

src = src.replace("\t", "    ")

f = open("D:/src.py", 'w')
f.write(src)
f.close()



2019/03/26 16:34

Ryu

import sys

with open(sys.argv[1],'r') as file:
    tab = file.read()

with open(sys.argv [1],'w') as file:
    file.write(tab.replace('\t',' '*4))

2019/04/07 12:10

Hwaseong Nam

```{.python}

```def tab_to_space(text): return text.replace('\t',' ')

2019/04/09 22:53

김민형

def solution(n): return n.replace(' ', ' ')

2019/04/20 14:58

이정택

Data = 입력받는 문자열 Result = 변환되어 사용자에게 리턴시켜주는 문자열

Data = input("Please Enter the Text : ")
Result = Data.replace(" ","    ")
print(Result)

2019/04/23 10:55

Gullen

my_file = input("Enter your file name : ")
#You must enter the file name extension!
f = open(my_file, "r")
data = f.read()
new = data.replace("\t","    ")
f.close()

f = open(my_file, "w")
f.write(new)
f.close()

2019/04/24 19:33

초보

with open('hello.txt', 'r') as file1: #탭으로 짜여진 소스코드를 불러온다
    str1 = file1.read()
    strCh = str1.replace('\t','    ') #탭을 공백4개로 변환
with open('hello_modify.txt', 'w') as file2: #변환된 내용저장하기 위한 hello_modify.txt 파일 생성
    str2 = file2.write(strCh) # 변환된 내용을 hello_modify.txt 에 저장

2019/05/02 21:01

MR SONG

filename = input('파일 이름을 입력하세요 :')

with open(filename, 'r') as f:
    data = f.read()
    data.replace('\t', '    ')

with open(filename, 'w') as f:
    f.write(data)

2019/05/10 21:45

messi

def tab_to_space(string):
    return string.replace("\t", "    ")


2019/05/14 21:50

Moonie08

line.replace("\t"," ")

2019/05/17 16:07

장재영

import os
import subprocess as sp

filepath = input("파일이 위치한 경로를 입력하세요(파일명 포함) : ")
ext = input("확장자를 입력하세요 : ")

with open("filepath", 'r') as f:
    srcContent = f.read()
    with open("filepath", 'w') as taptospace:
        taptospace.write(srcContent.replace("\t","    "))

2019/05/28 12:49

김선우

import re
import sys
def tabToSpace():
    print "file name" % sys.argv[0]

try : f = open(sys.argv[1])
except : tabToSpace(); sys.exit(2)

code = f.read()
f.close()
changedCode = code.replace("\t", " "*4)
f = open(sys.argv[1] , 'w')
f.write(changedCode)
f.close()

2019/05/29 10:57

가나다라

  1. 정규표현식과 replace를 사용하는 방법
function removeTab(targetString) {
  return targetString.replace(/\t/gi, "    ");
}
  1. split과 replace를 사용하는 방법
function removeTab(targetString) {
  return targetString.split("\t").join("    ");
}

2019/05/31 14:50

조대식

python3.6.7

import sys

input_file = sys.argv[1]
output_file = sys.argv[2]

fi = open(input_file, 'r')
tab_contents = fi.read()
fi.close()

space_contents = tab_contents.repalce('\t', ' '*4)

fo = open(output_file, 'w')
fo.write(space_contents)
fo.close()

2019/06/04 00:58

클레멘

a = open("before.txt", "r")
data = a.read()
a.close()

b=open("after.txt", "w")
b.write(data.replace("\t", " "*4))
b.close()

2019/06/04 16:44

Redoctseb

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open(dst, 'w')
f.write(space_content)
f.close()

2019/06/20 21:31

Firelight

#include <fstream>
#include <iostream>
#include <string>

using namespace std;


void main()
{
    string filePath;

    cout << "변환할 파일 경로 : ";
    std::getline(std::cin, filePath);

    ifstream fileIn(filePath);
    ofstream fileOut(filePath+".convert");

    char ch;
    while (!fileIn.eof())
    {
        ch = fileIn.get();
        if (ch == '\t')
            fileOut << "    ";
        else
            fileOut << ch;
    }
}

2019/06/26 19:13

캐니

def fileTap2Space(fname):                         
    with open(fname,'r') as f:
        data = f.read()
        data = data.replace('\t','    ')
    # 백업파일 이름 생성
    l = len(ext)
    a = fname[:-l]
    # 백업파일 생성
    with open(a + "_bak.txt",'w') as f:
        f.write(data)

    return data

'''
with as 구문
f.close필요 없음
자동으로 구문이 끝나면 f.close수행
'''
import os
_dir = input("_dir:")
ext = input("ext:")

for root, dirs, files in os.walk(_dir):
    for file in files:
        if file.endswith(ext):
            print(fileTap2Space(root+ '\\' + file))



# 재즐보프: 재미있게 즐기는 정보보안프로젝트! 코드 참고하였습니다.
# 백업파일 이름 부분만 추가한 코드입니다

2019/07/02 15:46

최은미

a=input('')
file=open('code.txt','w')
file.write(a)
file.close()
readfile=open('code.txt','r')
t=readfile.read()
t=t.replace('\t'," "*4)
readfile.close()
print(t)

2019/07/11 23:23

유선종

strList = []

with open('./tab.txt') as f:
    for s in f.readlines():
        strList.append(s.replace('\t', '    '))

with open('./space.txt', 'w') as f:
    for s in strList:
        f.write(s)

Python3

tab.txt에 있는 탭 문자를 공백 4개로 바꿔서 space.txt에 저장합니다.

2019/07/15 19:00

SilverCube

f = open('<source file path>', 'r')
fileContent = f.read()
f.close()

inputContent = fileContent.replace("\t", " "*4)

f = open('<source file path>', 'w')
f.write(inputContent)

2019/07/17 17:54

윤지수

def filetabReplace(fileNm):

    with open(fileNm, "r", encoding="UTF-8") as f:
        data = f.read()
        data = data.replace("\t", " " * 4)

    with open(fileNm, "w", encoding="UTF-8") as f:
        f.write(data)

print(filetabReplace("file.py"))

2019/07/31 18:18

dalbong

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open(dst, 'w')
f.write(space_content)
f.close()

교재 참고하였습니다.

2019/08/07 15:27

전근채

with open('test.txt','r') as fs:
    lines = fs.readlines()
with open('result.txt','w') as fw:
    for line in lines:
        i=0
        c=line[0]
        while ord(c) == 9:
            line = line[0:i] + ' '*4 + line[i+1:]
            i+=1
            c = line[i]
        fw.write(line)

2019/08/12 10:29

최재학

#! python3

import sys

sourceFile = open(sys.argv[1], 'r')
content = sourceFile.read()
sourceFile.close()

tabToSpace = content.replace('\t', ' ' * 4)

updatedFile = open(sys.argv[2], 'w')
updatedFile.write(tabToSpace)
updatedFile.close()

2019/08/20 12:57

S

def tab_to_space(s):
    s=s.replace('\t', ' '*4)
    return s

f=open('code.txt', 'r')
lines=f.readlines()
for line in lines:
    line = tab_to_space(line)
    f.write(line)
f.close()

2019/08/27 11:22

돔돔

str = input("글을 입력하세요: ")

if "\t" in str: str.replace("\t"," ") print('됏쪙') print (str)

2019/08/28 11:39

Cosu

        static void Main(string[] args)
        {
            string Path = @"C:\Test.txt";
            string [] ReadText = File.ReadAllLines(Path);
            StreamWriter WriteText = new StreamWriter(Path);

            foreach (string TextConvert in ReadText)
            {
                string Line = TextConvert.Replace("\t", "    ");
                WriteText.WriteLine(Line);
                Console.WriteLine(Line);
            }

            WriteText.Close();
        }

2019/09/03 10:26

김저승

f = open("013.txt", 'r')
tap = f.read()
f.close()
space = tap.replace("\t", " "*4)
f = open("013.txt", 'w')
f.write(space)
f.close()

2019/09/03 23:13

철쇄아

String str = "탭을    공백 문자로  바꾸기";
System.out.println(str.replace("\t", "    "));

2019/09/04 17:49

황재민

    String str = "dd\tdddf\tdfedfd";
        str.replaceAll("\t","    ");
        System.out.println(str);

2019/09/04 21:12

yeeun shim

str = lambda str : str.replace('\t', ' '*4)

2019/09/09 13:55

Entz

file = input('경로+이름+확장자 : ')

f = open(file, 'r')
f = f.read()
f_str = f.replace('\t','    ')

f = open(file, 'w')
f.write(f_str)
f.close()

2019/09/09 17:43

주희

PHP

// 임의 문자 생성
$str = "";
foreach(range(1, 10) as $n) {
    $str.= str_repeat("\t", $n)."tab{$n}\n";
}
// 탭 -> 공백 치환
$result = str_replace("\t", str_repeat("&nbsp;", 4), $str);
print_r($result);

2019/09/11 11:00

d124412

String = str(input("입력하세요 : "))

def tab_to_spaces(text): return text.replace("\t"," ")

print(tab_to_spaces(String))

2019/09/12 05:27

김민규

def tabspace(str1):
    return str1.replace("\t", "    ")

2019/09/12 11:02

김지원

#탭을 공백 문자로 바꾸기
f = open("tab.txt",'w')
data = r"DH\t:파이썬 잘하고 싶다.\t코딩은 어려워"
f.write(data)
f.close()

f = open("tab.txt", 'r')
line = f.read()
replace1 = line.replace(r'\t','    ')
print(replace1)
f.close()

2019/09/15 15:31

김다희

public class 탭을공백문자로바꾸기 {
    public String solution(String s) {
        String answer = s.replaceAll("\t", " ");
        return answer;
    }
    public static void main(String[] args) {
        탭을공백문자로바꾸기 a = new 탭을공백문자로바꾸기();

        System.out.println(a.solution("안녕하세요\t여러분\t제품소개\t입니다.\n잘부탁드립니다.\t지나가는\t이\t올림"));

    }
}

2019/09/22 03:47

전은광

def replace_indent(target_str):
    if(target_str[0] == '\t'): return (' ' * 4) + target_str[1:]
    else: return target_str

2019/09/23 14:28

Sangwoon Park

public class TabToSpace {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();
        str.replaceAll("\t", "    ");

        System.out.println(str);
    }
}

2019/09/28 02:36

Reviday

def Tab(text):
    result = text.replace('\t','    ') #' ' *4
    print(result)

Tab("abdd\tafgdg")

2019/10/02 17:54

semipooh

def tap_to_sapces(text): return text.replace("\t"," ")

2019/10/16 11:31

이뮤냑

import java.util.Scanner;

public class TapQuiz { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);

    String ans = "테스트1\t테스트2\t테스트3";

    System.out.println("변환 전 =>" + ans);
    ans = ans.replace("\t", " ");
    System.out.println("변환 후 =>" + ans);
}

}

2019/10/16 21:01

이유환

def change_ch(text):
    return a.replace('\t', ' ')

2019/10/19 19:49

이정석

import java.util.Scanner; //Scanner기능을 사용하기위해 필요함.
public class Replace {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String a = scan.nextLine();   //입력값을 문자로 받았다.
        a=a.replaceAll("\t", "    ");     //replaceAll을 이용하여 \t(tab)을 공백으로 바꿨다.
        System.out.println(a);     //값을 출력

    }

}

2019/10/28 20:50

big Ko

def change_ch(text):
    return text.replace('\t', ' ')

2019/11/01 09:36

data big

public class Sat1109 {

public static void main(String[] args) {
    String str = "abcde\tfghij\tabc\ted\tff";
    str = str.replaceAll("\t", "    ");
    System.out.println(str);
}

}

2019/11/09 16:49

김진혁

test = "space  and tab  tab tab "
test = test.replace('\t','    ')

2019/11/15 13:09

jcchoi

fname = "abc.py"
fname_new = "[MOD]" + fname
src_str = '\t'
chg_str = ' '*4

f = open(fname, 'r', encoding='UTF8')
f_str = f.read()
f.close()

f_str = f_str.replace(src_str,chg_str)
# print(f_str)

f = open(fname_new, 'w',encoding='UTF8')
f.write(f_str)
f.close()

python 3.7.2 / UnicodeDecodeError 고려 / 교육용 -코딩프렌즈-

2019/11/16 12:35

Jack Mountain

f1 = open('new.txt', 'r')
data = f1.read()
f1.close()

data.replace('\t', ' '*4)

f2 = open('code.txt', 'w')
f2.write(data)
f2.close

2019/11/17 18:29

YoungJun-Ryu

a.txt를 읽어서 탭을 스페이스 4개로 바꾸고 b.txt로 저장하도록 만들어봤습니다.

f = open('a.txt','r')
content = f.read()
f.close()

con_new = content.replace('\t',' '*4)

f = open('b.txt','w')
f.write(con_new)
f.close()

2019/11/21 22:39

GoNiee

#include <stdio.h>

int main(){
    char tab[] ="apple\tbanana\tpineapple\tmelon\twatermelonasdasdasdasdasdasdasdasdsdasd\tasdasdasdasdasda";
    int i,j,x=0;
    int a = sizeof(tab);
    for(i=0;i<a;i++){
        if(tab[i]=='\t')
        {
          x++;
          for(j=0;j<=a-i+2*x;j++){
            tab[a+4+2*x-j]=tab[a+1+2*x-j];
          }
          for(j=0;j<4;j++){
            tab[i+j]=' ';
          }
        }
    }
    printf("%s",tab);
    return 0;
}

2019/11/23 23:21

이준호

sample_txt = '''
안녕하세요. 탭테스트     
안녕히가세요. 공백 4개 테스트     
'''


def tabtos4(txt):
    ans_txt = sample_txt.replace('\t', '    ')
    print(ans_txt)


tabtos4(sample_txt)

파이선3.6 파일처리 생략

2019/11/26 14:56

DrKilling

가장 단순?하게 작성하였습니다.

#Chang Tab to 4Spaces
strIn = input('파일이름을 입력하세요 :: ')
strOut = strIn + '_out.txt'
f = open(strIn, 'r')
before = f.read()
f.close()
after = before.replace('\t','    ')
f = open(strOut,'a')
f.write(after)
f.close()
print('%s 파일이 생성되었습니다' % strOut)

2019/12/11 10:29

김영재

a = sourcecode.replace(" "," ") print(a)

2019/12/17 21:52

김희준

a=open("파일명.txt","r")
b=open("수정.txt",'w')
while True:
    line=a.readline()
    mod_line=line.replace(" ","    ")
    b.write(mod_line)
    if not line:break
b.close()

2019/12/18 05:33

김동석

include

void tab_to_space(char*original) { for (int i = 0; i < sizeof(original); i++) { if (original[i] == '\t') { original[i] = ' '; } } }

void main() { char tmp[] = "Hello, world! I am ANG JAE"; tab_to_space(tmp); printf("%s", tmp); }

2019/12/18 17:40

ANG JAE

f = open(tab_file)

tab_content = f.read()

f.close()

space_convert = tab_content.replace("\t"," "*4)

f.open(space_file,'w')

f.write(space_file)

f.close()

2019/12/21 12:13

HyukHoon Kim

mix_code = "tab\ttab    space    space"
print(mix_code)
mix_code = mix_code.replace('\t','')
print(mix_code)

2019/12/26 10:07

양파링

def tab_to_space(text):
    return text.replace('\t','    ')

2019/12/26 15:06

None

inputStr = input('문자를 입력하세요.')
if '\t' in inputStr:
    inputStr.replace('\t', '    ')
print(inputStr)

2020/01/04 12:50

안승현

a1=" 안녕하세요"
a2=a1.replace(" ","    ")
print(a1)
print(a2)

2020/01/21 13:57

스텔라stella

f1 = open("a.txt", 'w')
data = ("Life\tis\ttoo\tshort\nYou\tneed\tpython")
f1.write(data)
f1.close()

f1 = open("a.txt", 'r')
tab_content = f1.read()
space_content = tab_content.replace("\t", " "*4)
f1.close()
f2 = open("b.txt", 'w')
f2.write(space_content)
f2.close()

2020/01/26 16:00

Karinist xo

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)

tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)
print(space_content)

2020/01/27 14:45

손우진

def tab_to_space(text): return text.replace("\t", " " * 4)```{.python}

2020/02/03 16:58

이국성

def spacetr(s):
    s.replace('\t', '    ')
    return s

2020/02/07 09:47

KMH

    class Program
    {
        static string start = "\t안녕\t\t안녕안녕";
        static void Main(string[] args)
        {
            string result = start.Replace("\t", "    ");
        }

    }

2020/02/20 15:54

서주혁

import sys

tap_file = sys.argv[1]
space_file = sys.argv[2]

f = open(tap_file)
tap_content = f.read()
f.close()

space_content = tap_content.replace('\t',' '*4)


f = open(space_file, 'w')
f.write(space_content)
f.close()

2020/02/25 15:57

황예진

f=open("file directory", 'r')
data=f.read()
f.close()

g=open("file directory", 'w')
data=data.replace("\t", "    ")
g.write(data)
g.close()

2020/03/03 01:33

Caplexian _

file = input("enter file directory     ")
read1 = open(file, 'r')
data = tuple(read1.read())
write1 = open(file, 'w')
for i in range(len(data)):
    if data[i] == '\t':
        write1.write('    ')
    else:
        write1.write(data[i])
write1.close()

2020/03/05 12:36

with open(input('파일 이름을 입력하세요: ')) as f: contents = f.read()
contents = contents.replace('\t', ' '*4)
with open('result.txt', 'w') as f: f.write(contents)

2020/03/19 06:23

김정훈

code = "\tabcdef"
re_code = code.replace("\t", "    ")
print(re_code)

2020/03/27 20:40

조민섭

import java.util.*;

public class jony { public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();

a = a.replaceAll("\t", "    ");

System.out.println(a);

} }

2020/03/29 09:42

Jony

f = open("code.txt",'r')
data = f.read()
f.close()

datas = data.replace("\t"," "*4)

f=open('code.txt','w')
f.write(datas)
f.close()


2020/04/07 01:39

Lee Lee

sourcefile=open("source.py","r") writefile=open("new_source.py","w") while True: # line=sourcefile.readline() line=sourcefile.read() if not line: break line=line.replace("\t"," "*4) newLine=line.strip('\n') print(newLine) writefile.write(line) sourcefile.close() writefile.close()

2020/04/08 08:55

yhpdoit

f=open("test.txt",'r')
lines = f.readlines()
f.close()

f=open("test.txt",'w')
i=0
while i<len(lines):
     if lines[i]==None:
         break
     lines[i]=lines[i].replace('\t','    ')
     f.write(lines[i])
     i+=1
f.close()

2020/04/08 11:50

조윤재

def tab2space(tab): space = tab.replace(' ',' ') return space```{.python}

```

2020/04/18 22:12

박준하

def g(filename):
    f = open(filename, 'r')
    data = f.read()
    result = data.replace('\t', '    ')
    f = open(filename, 'w')
    f.write(result)
    f.close()
    print(result)

2020/04/19 23:00

ptjddn95

import sys

a=sys.argv[1]
b=sys.argv[2]

f=open(a)
atab=f.read()
f.close
bsp=atab.replace('\t','    ')

f=open(b,'w')
f.write(bsp)
f.close()

print(a)
print(b)

print(atab)
print(bsp)

2020/04/21 00:24

양양짹짹

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TapToSpace4 {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader("D:/desktop/Java/1.Tap.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:/desktop/Java/2.Space.txt"));

        String text;
        while ((text = br.readLine()) != null) {
            text = text.replaceAll("\t", "    ");
            bw.write(text + "\n");
        }
        br.close();
        bw.close();
    }
}

java

2020/05/01 21:12

Daniel Park

f = open("needfixed.txt",'r')
data = f.read()
f.close()

fixed = data.replace("\t", '    ')

f = open('needfixed.txt', 'w')
f.write(fixed)
f.close()


2020/05/06 22:46

Money_Coding

f = open('filename', 'r')
data = f.read()
f.close()

data_Replace = data.replace('\t', '    ')

f = open('filename', 'w')
f.write(data_Replace)
f.close()

2020/05/13 02:24

재미있는영상어디없나

#파이썬
fileName = input() #파일 이름 입력받기

try:
    file = open(fileName,'r') #파일을 r(읽기) 형식으로 오픈


except FileNotFoundError: #파일이 존재하지 않는 경우

    print('현재 디렉터리에 해당 파일이 존재하지 않습니다.')
    filestr = input('파일에 쓰고자 하는 내용을 작성해 주십시오:')

    file = open(fileName,'w')#파일 신규 생성 
    file.write(filestr)
    file.close()
    file = open(fileName,'r')

finally: #파일에 
    filestr = file.read()

file.close()


filestr = filestr.replace('\t','    ') #replace()를 이용해 filestr안의 \t문자를 '    '(공백문자 4개)로 변환

file = open(fileName,'w') #파일을 w(쓰기) 형식으로 오픈
file.write(str(filestr)) #변환한 내용을 파일에 덮어씀

file.close() 



##########################################
print(f'{fileName}이 변환되었습니다---')
file = open(fileName,'r')
filestr = file.read()
print(filestr)



2020/05/17 22:41

맛나호두

#파이썬


#역으로 공백 4개('    ')를 탭으로 변환해주는 프로그램


import re
try:
    fileName = input() #파일 이름 입력받기
    file = open(fileName)

except FileNotFoundError: #파일이 존재하지 않는 경우
    print('현재 디렉터리에 해당 파일이 존재하지 않습니다.')
    filestr = input('파일에 쓰고자 하는 내용을 작성해 주십시오:')

    file = open(fileName,'w')#파일 신규 생성 
    file.write(filestr)
    file.close()
    file = open('fileName.txt')
finally:
    filestr = file.read()
    file.close()

x = re.compile('[ ]{4}')#공백 4개인 부분을 찾는 패턴 생성[정규표현식]
filestr = x.sub('\t',filestr)#sub함수를 이용해 x에 대해 TRUE가 반환되는 부분을 탭으로 변환

file = open(fileName,'w')
file.write(filestr)

file.close()


##########################################
print(f'{fileName}이 변환되었습니다---')
file = open(fileName,'r')
filestr = file.read()
print(filestr)


2020/05/17 23:06

맛나호두

#파이썬
#텍스트 파일을 불러와서 변환후 화면으로도 출력을 하고
#파일로도 저장을 하는 소스입니다

import sys

fileopen=open("python.txt")
text=fileopen.read()

print ('원본텍스트\n',text)
replaced_text=text.replace('\t','    ')
print ('\n탭을 공백4칸으로 변환\n',replaced_text)
sys.stdout=open('python2.txt','w')
print(replaced_text)

2020/06/04 11:47

Buckshot

원본텍스트 def center(x): print (x,'\n--> ',end='') x.sort() if len(x)%2==0: print((x[int((len(x))/2)]+x[int((len(x)-1)/2)])/2) else: print(x[int((len(x)-1)/2)]) 탭을 공백4칸으로 변환 def center(x): print (x,'\n--> ',end='') x.sort() if len(x)%2==0: print((x[int((len(x))/2)]+x[int((len(x)-1)/2)])/2) else: print(x[int((len(x)-1)/2)]) - Buckshot, 2020/06/04 11:47
import sys

with open(sys.argv[1],"r") as f:
    lines=f.readlines()
    for i,line in enumerate(lines):
        lines[i]=line.replace(" \t","    ")

python 3

2020/06/05 10:06

조민동

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "haha\tdodo\tqpqp";
    while (str.find("\t") != string::npos) {
        str = str.replace(str.find("\t"), 1, "    ");
    }
    cout << str << endl;
    return 0;
}

C++

2020/07/02 14:25

채수현

    public static String tap_to_Space(String text) {
        text.replaceAll("\t", " ");
        return text;
    }

2020/07/14 17:28

허병우

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner s = new Scanner(System.in);
        String a="";
        a = s.nextLine();

        a = a.replace("\t", "    ");

        System.out.println(a);
    }

2020/07/16 19:46

Gosu TFT

public static String changeTabToSpace(String source) {
        source = source.replaceAll("\t", "    ");

        return source;
    }

2020/07/18 16:59

이소영

file1 = open("test.txt", "r", encoding="utf-8")
text = file.read()
with open("foo.txt", "w", encoding="utf-8") as f2:
    f2.write(text.replace("\t", "    "))

2020/07/29 21:22

김선민

import sys
import os

x = input("파일경로와 파일을 입력하세요 :")
filename = x
with open (filename) as file :
    transform_file = file.read()

change = file.replace('\t',"    ")
file = open(file,mode='w')
file.write(chage)
file.close()

2020/07/30 20:15

임선택


import java.io.*;
import java.util.*;
public class tabchange {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        List<Character> list = new LinkedList<Character>();
        try {

            FileReader fr = new FileReader("C:\\Users\\KK\\Desktop\\Study\\Test\\test.txt");
            BufferedReader rd = new BufferedReader(fr);

            FileWriter  fw = new FileWriter ("C:\\Users\\KK\\Desktop\\Study\\Test\\output.txt");
            BufferedWriter rw = new BufferedWriter(fw);

            int check;

            while( (check = rd.read()) != -1 ) {

                char mo = (char)check;

                if( mo == '\t') {
                    mo = ' ';
                    for(int i = 0 ; i < 4 ; ++i ) {
                        rw.write(mo);
                        //System.out.print(mo);
                    }
                }
                else {
                    rw.write(mo);
                    //System.out.print(mo);
                }
            }
            fr.close();
            fw.close();


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }
}



2020/08/17 14:13

kkd0153

asd

2020/08/19 09:30

이동욱

f=open('abc.txt','w')
f.write('my\tname\tis\tpython')
f.close()
f=open('abc.txt','r')
a=f.read()
f.close()
b=a.split()
c='    '.join(b)
f=open('abc.txt','w')
f.write(c)
f.close()

2020/08/26 17:55

Konyul Park

f = open("sample.txt")
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open("sample_new.txt", 'w')
f.write(space_content)
f.close()

2020/09/05 23:41

BigMango

import java.util.Scanner;

public class Revision{
public static void main(String[] args){
String a = new Scanner(System.in);
a1 = a.replaceAll('\t', '    ');
System.out.print(a1);
Scanner.close();
}
}

이렇게 풀어봤습니다. replaceAll() 함수를 이용했습니다.

2020/10/03 16:01

eumeum2eumeum

import glob
import re
import shutil

class DoConversion:
    def __init__(self):
        pass
    def replaceTab(self):
        b = glob.glob("*.src")
        for i in b:
            print(i)
            f = open(i,"r")
            t = open("temp.src","w")
            while True:
                line = f.readline()
                if not line:
                    break
                p = re.compile(r'\t')
                m = p.search(line)
                if m:
                    line = line.replace("\t","    ")
                t.write(line)
            f.close()
            t.close()
            shutil.move("temp.src",i)

a = DoConversion()
a.replaceTab()

2020/10/03 17:02

footsize

파이썬입니다. 임의의 파일 'test_text.py' tab이 있는 for loop 의 짧은 코드입니다. f.read() 와 f.readlines() 차이는 아직 잘 모르겠네요. readlines()는 리스트로 돌려줘서 for loop을 통해 replace()를 써봤는데 바뀌지 않는것 같아 read()로 작성했습니다.

f = open('test_text.py', 'r+')
read = f.read()
temp_read = read.replace('\t', '    ')
new = open('new_read.py', 'w')
new.write(temp_read)
new.close()
f.close()

2020/10/10 19:06

방금프로그래밍시작함

import tkinter as tk
from tkinter import filedialog
root=tk.Tk()
root.withdraw()
file_path=filedialog.askopenfilename()
f = open(file_path)
f1 = f.read()
f1 = f1.replace("\t", "    ")
f = open(file_path, 'w')
f.write(f1)
f.close()

2020/10/13 08:58

aryagaon

python 여러 파일이 있다고 가정한 후, replace 탭을 공백*2로 바꾸고, 체크하는 함수까지 넣어봤습니다.

실제로 들여쓰기 통일화를 위한 업무 자동화 코드를 짜야 한다면, 복잡해 질 것 같네요.

고수님들 코드 잘 보고 배워갑니다.

import os

# 지정한 패스의 모든 .py 파일 가져오기
def get_file_path():
  pathlist = []
  path = os.getcwd() + "/quiz/codingDojang/Python-Algorithm/002_source_code_file"
  for root, dirs, files in os.walk(path):
    for file in files:
      if file.endswith(".py"):
        pathlist.append(root + "/" + file)
      else: pass
  return pathlist

# 파일 읽기, 수정하기, 저장하기
def file_read_write():
  pathlist = get_file_path()
  for path in pathlist:
    new_lines = []
    with open(path, "r") as f:
      lines = f.readlines()
      for line in lines:
        new_lines.append(line.replace("\t", " "*4))

    with open(path, "w") as f:
      f.writelines(new_lines)

file_read_write()

def check_work():
  pathlist = get_file_path()
  for path in pathlist:
    _file = open(path)
    if _file.read().find("\t") != -1:
      raise Exception("코드에 탭을 찾았습니다.")
    else:
      print("파일이 정상입니다. 검사 완료.")

2020/10/14 22:08

vcne0705

package dojang;

import java.util.Scanner;

public class Replaceblackbox {

public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);
    System.out.println("글들을 넣어 보세요.");
    String a=sc.nextLine();//next보다 nextline이 적합 엔터나 탭 잡아야 함
    a=a.replace("\t","    ");
    System.out.println(a);
}

}

2020/10/28 22:57

SIA

package Practice;
public class TabToSpacebar {
    public static void main(String[] args) {
        String text = "Hi my name is Java\tI'm your friend\tand i'm so proud of you.";
        System.out.println(text);
        System.out.println(TabChanger(text));
    }
    private static String TabChanger(String text) {
        String ChangeTab = text.replaceAll("\t", "    ");
        return ChangeTab;
    }
}

2020/10/30 15:22

장우상

public String text() {
    text = null;
    text.replaceAll("\t", "    ");
    return text;

2020/11/03 19:00

김지헌

filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()

2020/11/03 20:04

고태욱

import sys
src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f.open(dst, 'w')
f.write(space_content)
f.close

2020/11/05 08:45

DSHIN

import sys


def tab2gap(i):
    return i.replace("\t", " " * 4)


del sys.argv[0]
i = sys.argv[0]
o = sys.argv[1]

with open(i, 'r') as f:
    with open(o, 'w') as f2:
        f2.write(tab2gap(f.read()))

2020/11/12 14:16

김우석

package codeDojang;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;



public class Prac {
    public static void main(String[] args) throws IOException {

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("test.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("경로에 파일이 존재하지 않습니다.");
        }

        String line = null;
        String tmp="";
        while((line = br.readLine())!=null) {
            if(line.contains("\t")) {
                tmp+=line.replace("\t", "....");
            }
            tmp+=line+"\n";
        }



        BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));
        bw.write(tmp);
        bw.close();





    }
}


공백대신 ....으로 표시함

2020/11/18 11:33

yijun kim

File_Name=input("write your file name")

f.open(File_Name,"r")

data=f.read()

f.close()

data.replace("\t"," ")

2020/11/20 15:28

전준혁

import java.util.Scanner;

public class pro2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        String a = sc.nextLine();
        String b = a.replace("\t", "    ");
        System.out.println(a);
        System.out.println(b);
    }

}

2020/12/07 20:05

이정섭

a = input("소스코드를 텍스트 파일로 저장하고 저장경로를 입력하세요: ")

print(a)

with open("{}".format(a), 'r') as f:
    lines = f.readlines()

print(lines)


with open("{}".format(a), 'w') as f:
    for j in range(0, len(lines)):
        data = lines[j].replace("\t", "  ")
        f.write(data)


print("소스코드 내 모든 \t을 공백4개로 바꾸었습니다. 저장된 파일을 복사하여 사용하세요.")

2020/12/09 15:47

코딩뚜

파이썬 3.7.2 버전입니다.

def foo():
    file_name = input('파일명을 입력해 주십시오 : ')

    row_file = open(file_name, 'r', encoding = 'UTF-8')
    lines = row_file.readlines()
    row_file.close()

    modify_lines = [line.replace('\t', ' '*4) for line in lines]

    modify_file = open('modify_'+file_name, 'w', encoding = 'UTF-8')
    for line in modify_lines:
        modify_file.write(line)
    modify_file.close()

foo()

2020/12/15 15:44

최병찬

파이썬입니당

files=input('파일경로:')
with open(files,'r') as f:
    text=f.read()
text=text.replace('\t','    ')
with open(files, 'w') as f:
    f.write(text)

2020/12/20 00:04

형제는못말려

def howmanyT(word):
    count = 0
    store1 = []
    store2 = []
    new = ''
    for i in range(0, len(word)):
        if word[i] == '\t':
            count += 1
            store1.append(i)
    if store1 == [] and count == 0:
        return word
    elif store1 != []:
        for b in range(len(word)):
            store2.append(word[b])
        for c in store1:
            store2[c] = '    '
        for d in store2:
            new += d
    return new


def tabtoSpace(filename):
    store = []
    for i in open(filename, 'r'):
        edited = ''
        line = i.split(' ')
        for w in line:
            edited += howmanyT(w) + ' '
        edited = edited[0:len(edited)-1]
        store.append(edited)
    f1 = open(filename, 'w')
    for i in store:
        f1.write(i)
    print('complete')
tabtoSpace('test1.txt')

2020/12/21 22:09

Chiu Choi

name =input("파일 이름을 입력하세요.: ")
text = open(name)
text_ =text.read().replace('\t','    ')
text= open(name,'w')
text.write(text_)
text.close()

2020/12/22 22:32

hankyu

import sys

name1 = sys.argv[1]
name2 = sys.argv[2]
f = open(name1,'r')
all = f.read()
f.close()

all = all.reaplce('\t',' ' * 4)

f1 = open(name2,'w')
f1.write(all)
f1.close()

2020/12/28 13:16

박성진

f = open("tab_content.txt", "r")
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t","    ")

f = open("space_content.txt", "w")
f.write(space_content)
f.close()

파이썬으로 작성했습니다.

작성된 코드를 tab_content.txt로 가정하고 코딩하였습니다.

2020/12/28 16:54

임준혁

with open('bbb.txt', 'w') as file:
    with open('aaa.txt', 'r') as f:
        for line in f.readlines():
            line = line.replace('\t', '    ')
            file.write(line)

2021/01/15 12:32

asdfa

[파이썬]

before = open("C:/Users/Home/Desktop/tab.txt", 'r')
after = open("C:/Users/Home/Desktop/4space.txt", 'w')

tab_contents = before.readlines()

for i in tab_contents:
    j = str(i)  # 요소를 str로 바꾸고
    k = j.replace("\t", "    ")  # 탭을 스페이스 4번으로 바꾼 뒤 k에 저장해줍니다
    after.write(k)  # 바꾼 k의 내용을 4space.txt에 써줍니다

before.close()
after.close()

2021/02/02 16:05

PenLoo


public class mate {
    public static void main(String[] args) {
        String text = "Hello\tmy\tname\tis";

        text = text.replaceAll("\t", "    ");
        System.out.println(text);
    }
}

2021/02/22 16:26

미래해

name=input("file name : ")
str=open(name).read().replace("\t","    ")
file=open(name,'w').write(str)

2021/03/26 17:11

팀운

def replace(filename, original = "\t", replaced = "    "):
    with open("filename", "r") as f:
        codes = f.read()
        codes.replace(original, replaced)
    with open("filename"+"_rep", "w") as f_:
        f_.write(codes)

<파이썬 3>

2021/04/04 09:20

Ruo Lee

셸 스크립트입니다.

파일명: tab2space

cp $1 $1.bak
sed 's/\t/    /' $1.bak > $1

사용법:

$ sh tab2space prg.py

2021/04/11 03:55

최용

def tab_convert_to_space4(filename):
    open_file = open(f"{filename}.txt", 'r', encoding='utf8')
    allfile = open_file.read()
    allfile = allfile.replace("\t",'    ')
    open_file.close()
    writefile = open(f'{filename}_invert.txt', 'w', encoding='utf8')
    writefile.write(allfile)
    writefile.close()

2021/04/15 22:11

whalerice

def tab_convert_to_space4(filename):
    open_file = open(f"{filename}.txt", 'r', encoding='utf8')
    allfile = open_file.read()
    allfile = allfile.replace("\t",'    ')
    open_file.close()
    writefile = open(f'{filename}_invert.txt', 'w', encoding='utf8')
    writefile.write(allfile)
    writefile.close()

2021/04/15 22:11

whalerice

String filePath = "C:\\home\\test.txt";
//파일 객체 생성
File file = new File(filePath);
String strText = "";
int nBuffer;

//파일 읽기
try{
  BufferedReader buffRead = new BufferedReader(new FileReader(file));
  while((nBuffer = buffRead.read()) != -1){
    strText += (char)nBuffer;
  }
  buffRead.close();
}

catch (Exception e) {
  System.out.println(e.getMessage());
}

System.out.println(strText);
//파일이 없을경우 파일생성
if(file.exists() == false) {
  try {
    int nLast = filePath.lastIndexOf("\\");
    String strDir = filePath.substring(0, nLast);
    String strFile = filePath.substring(nLast+1, filePath.length());
    File dirFolder = new File(strDir);
    dirFolder.mkdirs();
    File f = new File(dirFolder, strFile);
    f.createNewFile();
  }

  catch (Exception e) {
    System.out.println(e.getMessage());
  }
}

//파일 수정
try {
  BufferedWriter buffWrite = new BufferedWriter(new FileWriter(file));
  String Text = strText.replace("\t", "    ");
  buffWrite.write(Text, 0, Text.length());
  buffWrite.flush();
  buffWrite.close();
}catch (Exception e) {
  System.out.println(e.getMessage());
}

2021/04/26 17:16

jaesung kim

python 3.9입니다. 실행할 때 python example.py (탭 파일 디렉토리) (공백 파일 디렉토리) 식으로 실행합니다. 소스:

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src, 'r')
body = f.read()
f.close()

replaced = body.replace('\t', ' '*4)
f2 = open(dst, 'w')
f2.write(replaced)

print('processed successfully')

실행법:

C:\Users\82105>cd C:\Users\82105\Desktop\이준우\python\simple_programs\codingdojang

C:\Users\82105\Desktop\이준우\python\simple_programs\codingdojang>python coding19.py C:\Users\82105\Desktop\이준우\python\simple_programs\tab.txt C:\Users\82105\Desktop\이준우\python\simple_programs\four_space.txt
processed successfully

C:\Users\82105\Desktop\이준우\python\simple_programs\codingdojang>

tab.txt 내용: (각 공백은 탭 문자)

1   2   3   4   5

four_space.txt 내용: (각 공백은 스페이스 4개)

1    2    3    4    5

2021/04/30 11:59

이준우

tab과 공백4칸의 차이인 2칸을 lstrip으로 없애주고 다시 2칸을 전체에 들여쓰기 해보았습니다.

renew = sourcecode.lstrip(" ") print(" ",renew)

2021/05/06 10:13

ss2663

파이썬 시작한지 얼마 되지않아 이런 간단한 코드로 밖에 못쓰겠네요 ㅠ

a = "\t" * 4

if a == "\t" * 4:
    a = end=" " * 4
    print(a)
#    a = end=" "
#    print((a+".")*4)

2021/06/08 16:29

qazxsw12

py=input("file name : ")

with open(py, 'r') as f:
    data = f.read()
    f1 = data.replace("\t", "    ")

with open(py, 'w') as f:
    f.write(f1)

2021/06/22 20:29

inkuk ju

f = open('file.txt','r')
body = f.read()
f.close()

body = body.replace('/t','    ')

f = open('file.txt','w')
f.write(body)
f.close()

2021/06/24 23:09

SH LEE

def tab_to_space(text):
    return text.replace("/t", "    ")

2021/06/29 19:50

김준규

#coding_dojang: tabto4


def tabto4(file):
    result = ''

    with open(file, 'r') as fr:
        result = fr.read()

    with open(file, 'w') as fw:
        fw.write(result.replace('\t', '    '))


tabto4(filename)


2021/07/06 17:03

Jaeman Lee

a = open('tab','r') b = a.readlines() a.close()

c = b.replace("\t"," ") a = open('tab','w') a.write(b) a.close

2021/07/08 21:28

Youngchul Kwon

a = input() b = a.replace("/t", "' '*4") print(b)

2021/07/19 16:18

서현준

    public static void main(String[] args) {
        String inputData = "테스트 테스트 테스트 테스트 "; 

        System.out.println(test(inputData));
    }

    public static String test(String inputData) {
        return inputData.replaceAll("\t", "    ");
    }

2021/07/23 14:08

tm k

filename = input("파일 이름을 입력하세요: ")
file = open(filename, 'r')
file = file.read()
newFile = file.replace("\t", " "*4)
file = open(filename, 'w')
file.write(newFile)
file.close()

2021/07/30 15:21

deeoning


import sys
src = sys.argv[1]
dst = sys.argv[2]

with open(src, 'r') as f:
    lines = f.readlines()

newline = []
for line in lines:
    if line[0] == "\t":
        newline.append("    " + line[1:])
    else:
        newline.append(line)

with open(dst, 'w') as f:
    f.writelines(newline)

2021/08/06 00:39

Jinuk Kim

package exam;

public class Ex03 {


    public static void main(String[] args) {

        String str = "public\tstatic\tvoid\tmain";
        System.out.println(str);

        str = str.replaceAll("\t", "    ");

        System.out.println(str);

    }
}

java

2021/08/10 21:40

전채

from os import replace

a = str(input('수정할 파일 이름 : ',))
b = str(input('저장할 파일 이름 : ',))


f = open(a, 'r', encoding='UTF-8')
line = f.read()
filetext = line.replace('\t',' '*4)
f.close()
f = open(b, 'w', encoding='UTF-8')
f.write(filetext)
f.close()

2021/08/21 12:29

Beom Yeol Lim

with open('txt','r') as file:
    line = file.read()
    line = line.replace("\t", "    ")
    with open('txt', 'w') as file2:
        file2.write(line)

2021/09/02 12:09

Ha

    <script>
let str ="apple,    ,banana, orange,    ,banana";
let replaced_str=str.replace(/  /gi,"tomato");

console.log(replaced_str)
    </script>

2021/09/03 15:45

김운성

package test1;

import java.util.Scanner;

public class test2 {
    public static void main(String[] args) {

        System.out.print("소스코드 입력 : ");
        Scanner sc = new Scanner(System.in);

        String sourceCode = sc.next();

        sourceCode.trim();

        String finalCode = "    " + sourceCode;

        System.out.println(finalCode);

        sc.close();
    }
}

2021/09/07 14:58

junghyun

# replace 1 tap with 4 spaces

code = input("코드를 입력하세요.")

temp = code.split("\t")
print(temp)

# f = open("file name")
# code = f.read()

code.replace("\t", "    ")
code = code.split("\t")
print(code)

2021/09/30 14:25

송효근

filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()

2021/10/10 16:33

슬로싱커

    public static void main(String[] args) {
        String str = "\t안녕\t";
        System.out.println(str);
        str = str.replace("\t", "    ");
        System.out.println(str);
    }

2021/10/13 16:41

박대현

import os

def tab2space(fname):
    with open(fname, 'r', encoding='UTF8') as f:
        data = f.read()
        data = data.replace('\t', ' '*4)
    with open(fname, 'w', encoding='UTF8') as f:
        f.write(data)

dir_ = input('dir_: ')
ext = input('ext: ')

for root, dirs, files in os.walk(dir_):
    for file in files:
        if file.endswith(ext):
            print(tab2space(root + '/' + file))

2021/10/18 11:47

Jinsol


import sys
src = sys.argv[1]  # 탭을 포함하고 있는 파일명
dst = sys.argv[2]  # 탭을 공백 4개로 변환한 결과를 저장할 파일명

f = open(src)
tab_contest = f.read()
f.close()
space_content = tab_content.replace("\t", " " *4)

f = open(dst, 'w')
f.write(space_content)
f.close()

2021/11/15 12:24

갈매기형님

n = input("소스코드를 입력하세요 : ")
for i in n:
    if i == "/t":
        i = " "*4

2021/12/09 13:52

Sanghun Lee

name = input("파일 경로를 입력하세요:")

f = open(name)
f = f.read()
f_str = f.replace('a','b')
f = open(name,'w')
f.write(f_str)
f.close()

2021/12/14 16:47

김대연

f = open('C:\pythoncoding1/t1.txt','r')
a_str = f.read()

b = a_str.replace(" ","    ")
print(b)

2021/12/14 23:51

양캠부부

python입니다.

def Tab(i):
    Space=i.replace('   ','    ') and i.replace('\t','    ')

    return Space

a="Hello    Hi\tbye"
print(Tab(a))

2021/12/15 19:25

김시은

public class Ex02 {
    public static void main(String[] args) {
        String str = "ABCD  EFGF        sd";
        tab(str);
    }   

    static void tab(String doc) {
        doc = doc.replaceAll("\t", "    ");
        System.out.println(doc);
    }
}

2021/12/18 16:01

박준모

path = input("open 할 file 입력 : ")

f = open(path,'r')
data = f.read()
data.replace('\t','    ')
f.close()

f = open(path.'w')
f.write(data)
f.close()

2022/01/05 18:27

강태호

import sys

src = sys.argv[1]
dst = sys.argv[2]

f = open(src)
tab_content = f.read()
f.close()

space_content = tab_content.replace("\t", " "*4)

f = open(dst, 'w')
f.write(space_content)
f.close()

2022/02/04 14:47

qkrthals

def tab_to_space(code):
  code.replace('\t', '    ')
  return code

2022/02/08 23:05

최재형

파이썬입니다 import sys

f = open("/Users/tastebread/PycharmProjects/a.txt",'r') tab_content = f.read() f.close()

space_content = tab_content.replace("\t"," "*4) print(space_content)

2022/02/28 15:10

김태현

fileOne = open('file1.txt','r')
fileTwo = open('file2.txt','w')
data = fileOne.read()
data = data.replace('\t','    ')
fileTwo.write(data)
fileOne.close()
fileTwo.close()

2022/04/12 23:59

고구마츄

print(a.replace("\t"," "))

2022/04/14 15:28

yunjae

package com.algorithm.algorithmpractice.dojang;

public class tabtospace {
    //    A씨는 개발된 소스코드를 특정업체에 납품하려고 한다.
//    개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다.
//    A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
//    A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.

    public static void main(String[] args) {
        String code = "\t1\t123\tzas\tdfd\tasf\tas\tdf";

        String result = code.replace("\t", "    ");

        System.out.println(result);
    }
}

2022/04/23 12:21

inkuk ju

path=input() file=open(path, 'r', encoding="UTF8") lines=file.readlines() for line in lines: line=line.replace("\t", " ") print(line) file.close()

2022/05/04 19:16

권덕재

    int c;

    while ((c = getchar()) != EOF)
    {
        if (c != '\t')
        {
            putchar(c);
        }

        if (c == '\t')
        {
            printf("    ");
        }
    }

2022/05/19 11:57

rh

public static void main(String[] args) {

        /* *문제*
           A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 
           개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. 
           A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
           A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오. */

        String str = "\t";
        System.out.println(str);
        str.replaceAll("\t", "    ");
        System.out.println(str);

    } // main

맞는지 잘 모르겠습니다 코드보시고 리뷰좀해주세요ㅠ_ㅠ

2022/05/20 14:48

김태형

# python

import sys

first = sys.argv[1]
second = sys.argv[2]

with open(first, "r") as f:
    data = f.read()

with open(second, "w") as f:
    data2 = data.replace("\t", " " * 4)
    f.write(data2)

2022/06/10 21:27

goodsoul

def f(x):
    return x.replace('\t','   ')

파이썬입니다

2022/07/06 21:40

Hote

c#입니다. replace 안쓰고 싶어서 해봤어요

public static string Replace(string sentence)
        {
            // "   " => "    "
            int cnt = 0;
            StringBuilder text = new StringBuilder();

            while (sentence.Length > cnt)
            {
                if (sentence[cnt] == '\t')
                {
                    text.Append("    ");
                }
                else
                {
                    text.Append(sentence[cnt]);
                }
                cnt++;
            }

            return text.ToString();
        }

2022/07/18 16:14

블랙로켓

f1 = open("source_code.py", 'r')
f2 = open("source_code_new.py", 'w')

lines = f1.readlines()
for x in lines:
    x = x.replace('\t', '    ') # 탭을 공백 4개로 바꾸기
    print(x, file=f2)

f1.close()
f2.close()

2022/07/25 15:34

세라

file = input("파일 이름을 입력하세요.:")
try:
    f = open(file, 'r')
except FileNotFoundError:
    pass
    file = input("파일을 읽을 수 없습니다. 파일 이름을 다시 입력하세요.:")

content = f.read()
change = content.replace('\t','    ')
f.close()

f = open(file, 'w')
changed = f.write(change)
f.close()

print("파일 내의 탭 문자가 공백 4개로 수정되었습니다.")

2022/07/28 20:32

아이스카페모카

filename = '새파일.txt'
with open(filename, 'r') as f:
    line = f.read()
with open(filename, 'w') as f:
    f.write(line.replace('\t', '    '))

2022/08/07 19:40

JayK

public class ReplaceTabWithSpace {
    public void solution(String params) {
        String[] tabArr = this.splitByTab(params);
        String result = this.replaceTabWithSpace(tabArr);
        System.out.println(result);
    }

    // ==== private ====
    private String[] splitByTab(String str) {
        String[] arr = str.split("\t");
        return Arrays.stream(arr)
                .filter(s -> s.length() > 0)
                .toArray(String[]::new);
    }
    private String replaceTabWithSpace(String[] strArr) {
        StringBuilder builder = new StringBuilder();
        for (String s : strArr) {
            builder.append("    ").append(s);
        }
        return builder.length() > 0 ? String.valueOf(builder) : "";
    }
}

2022/08/12 23:19

정이언

2022/08/15 14:27

JML

def tabToSpace4():
    with open('source.txt','r') as f:
        source=f.read()
    with open('source.txt','w') as f:
        changedSource=source.replace("\t", "    ")
        f.write(changedSource)
    print(changedSource)

tabToSpace4()

2022/08/15 14:37

JML

Python re.sub 를 활용한 변경방법

write_f = open('./sample/content_with_whitespace.txt', 'w')
read_f = open('./sample/content_with_tab.txt', 'r')

write_f.write(re.sub("\t", ' '*4, read_f.read()))

read_f.close()
write_f.close()

2022/08/31 14:02

최영훈

'''
#make before code include tab
f=open("scr.txt",'w')
sourcecode="""
sum=0
for i in range(1000):
    if i%3==0 or i%5==0:
        sum+=i

print(sum)"""
f.write(sourcecode)
f.close()
'''
#read before code include tab
f=open("scr.txt",'r')
codeTab=f.read()
f.close()
print(codeTab)

#tab->space*4
codeSpace=codeTab.replace("\t"," "*4)

#revision
f=open("scr.txt",'w')
f.write(codeSpace)
f.close()


2022/09/14 14:03

yongju Lee

package test;

public class Ex14 {

public static void main(String[] args) {
    String file = "";
replace(file);
}

public static String replace(String file) {
    file.replace("\t", "    ");
    return file;
}

}

2022/10/16 10:23

김록길

string = ""
with open("result.txt", "w") as f:
    f.write(string.replace("/t", "    "))

2022/11/05 01:04

Seojin

str = str.replace(/\t/g," ");

2022/11/25 16:34

김동훈

코드 입력값

code = input('Q. 탭을 공백4개로 변경할 코드를 입력하세요: ')

교체하기

code_rev = code.replace('\t', ' ')

결과물 제시

print(code_rev)

2022/11/26 20:01

ROHANA

public class Tab2Space {
    public String convertTab2Space(String originStr){
        String returnString = null;
        if (originStr != null) {
            returnString = originStr.replace("\t", "    ");
        }
        return returnString;
    }
}

2022/12/31 21:45

강아지

str1=input() str2="" for i in str1: if i==chr(9): str2=" " else: str2=str2+i print(str2)

2023/03/07 19:21

Sol Song

f = open("./cord.txt.", 'r') #파일이름은 가정 lines = f.readlines() f.close() f = open("./revise.txt", 'w') #없으면 파일 생성 for line in lines: f.write(line.replace("\t", " ")) f.close()

2023/03/18 20:39

최준하

f = open('file', 'r')
f_rev = open('file_rev', 'w')

lines = f.readline()
for line in lines:
    line_rev = line.replace('\t', ' '*4)
    f_rev.write(line_rev)

f.close()
f_rev.close()

2023/05/01 14:39

Jisook

with open('file','r') as f:
  contents=f.read()
modified_cont=contents.replace('\t',' '*4)
with open('file','w') as f:
  f.write(modified_cont)

2023/05/06 23:56

hbyun

f=open('a.txt','r',encoding='utf-8')
lines=f.readlines()
for line in lines:
    line=line.strip()
    line=line.replace('\t',' '*4)
    print(line)
f.close()

2023/06/13 10:37

ddd

public class SelfTest_2 {
    public static void main(String[] args) {
        String text = " tab change  to   space";
        text = text.replace("\t", "    ");
        System.out.println(text);
    }
}

2023/06/16 10:30

JongHo Han

def tab_to_spacex4(text):
    return text.replace('\t,'    ')

2023/06/18 23:57

NH Kim

package codingstamp.ex019_Lv1;

import java.util.Scanner;

public class trialAndError {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 우선 키보드 입력을 받아준다.
        String str = sc.nextLine();
        str = str.replace("\t", "    ");
        System.out.println(str);
    }
}

2023/06/29 23:41

심상균

def replace_tabs_with_spaces(input_file, output_file): with open(input_file, 'r') as file: source_code = file.read()

modified_code = source_code.replace('\t', '    ')  # 탭을 공백 4개로 대체

with open(output_file, 'w') as file:
    file.write(modified_code)

if name == "main": input_file = "input_source_code.txt" # 입력 파일의 이름을 여기에 지정 output_file = "output_source_code.txt" # 수정된 소스코드를 저장할 파일 이름을 여기에 지정

replace_tabs_with_spaces(input_file, output_file)

2023/09/17 15:13

세이건칼

```{.python} str_src = "\tsome\tthing something \tsomething something\t something" revised_src = str_src.replace("\t"," ") print(revised_src) print(revised_src.find("\t"))

탭 문자를 찾을 수 없음으로 -1을 출력한다!

2024/01/31 20:08

김인수

# 파일을 열기 -> replace('\t', ' '*4)사용 -> 새로운 파일에 저장
import os
def NO_tab(input_file, output_file):
    with open(input_file, 'r') as f:
        content = f.read()

     just_spaces = content.replace('\t', ' ' * 4)

    with open(output_file, 'w') as file:
        file.write(just_spaces)

if __name__ == '__main__':
    input_file = 'input_code_file.txt'  
    output_file = 'output_code_file.txt'  
    NO_tab(input_file, output_file)

2024/08/09 17:22

먼지

indentTab2space = lambda x,w: len(x.split())>0 and x[:x.find(x.split()[0])].replace('\t',' '*w)+x[x.find(x.split()[0]):] or ''
print(indentTab2space('\t \tif 조건: print(" 테스트 탭\t테스트 ")', 4))
>         if 조건: print(" 테스트 탭  테스트 ")

2024/10/07 06:25

무므뭇

def replace_tabs_in_code(): import inspect

current_code = inspect.getsource(replace_tabs_in_code)

modified_code = current_code.replace('\t', '    ')

print("===== 수정된 코드 =====")
print(modified_code)```{.python}

```

2024/11/25 14:49

YOUNGHWAN KIM

def tab_to_4spaces() :
    # input of the file name of the source code
    file_name = input('Enter the file name : ')

    # output of the original code
    with open(file_name, 'r') as before :
        original_code = before.read()        
    print('Original code is : \n', original_code)

    # transformation of tab to 4 spaces
    changed_code = original_code.replace('\t',' '*4)

    # output of the transformed code
    print('Changed code is : \n', changed_code)
    print('\n')

    # confirmation of the changed code 
    with open('changed_file.txt','w+',encoding='utf-8') as after :
        after.write(changed_code)
        after.seek(0)
        print('In changed_file : ', after.read())  

2024/12/02 13:00

Orange

JAVA입니다.

package 탭을_공백_문자로_바꾸기;

import java.io.FileReader;

public class ReplaceTab {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        FileReader fr = new FileReader(ReplaceTab.class.getResource("code.txt").getPath());
        while(true) {
            int read = fr.read();
            if(read == -1) {
                break;
            }
            String s = Character.toString((char) read);
            if(s.equals("\t")) {
                s = "    ";
            }
            System.out.print(s);
        }
    }

}

2025/01/22 20:51

박준우

code="#include <stdio.h>\n\nint main(void)\n{\n    printf(\"hello, world.\");\n\treturn 0;\n}"

print(code)

list_code=list()
for a in code:
    if a=='\t':
        list_code.append('    ')
    else:
        list_code.append(a)

print(list_code)

print(''.join(list_code))

2025/03/05 11:25

박성우

import os

def replace_indent_tabs(path):
    with open(path, "r", encoding="utf-8") as f:
        lines = f.readlines()

    new_lines = []
    for line in lines:
        idx = 0
        while idx < len(line) and line[idx] == '\t':
            idx += 1

        indent_spaces = "    " * idx

        remainder = line[idx:]

        new_lines.append(indent_spaces + remainder)

    # 파일 덮어쓰기
    with open(path, "w", encoding="utf-8") as f:
        f.writelines(new_lines)

2025/11/23 12:36

k

import promptSync from 'prompt-sync';

const prompt = promptSync();

function convertTabToSpaces(code: string): string {
  return code.replace(/\t/g, "    ");
}

const input = prompt("문자열 입력: ");

console.log(convertTabToSpaces(input));

2026/03/09 16:15

noa

filename = input('Enter your file name: ')

with open(filename, 'r', encoding='utf-8') as f:
    data = f.read()

data = data.replace('\t', '    ')

with open('result.txt', 'w', encoding='utf-8') as f:
    f.write(data)

2026/05/14 00:39

우영재

목록으로