开发者

Problems with Python's file.write() method and string handling

The problem I am having at this point in time (being new to Python) is writing strings to a text file. The issue I'm experiencing is one where either the strings don't have linebreaks inbetween them or there is a linebreak after every character. Code to follow:

import string, io

FileName = input("Arb file name (.txt): ")

MyFile = open(FileName, 'r')

TempFile = open('TempFile.txt', 'w', encoding='UTF-8')

for m_line in MyFile:
    m_line = m_line.strip()
    m_line = m_line.split(": ", 1)
    if len(m_line) > 1:
        开发者_高级运维del m_line[0]
    #print(m_line)
    MyString = str(m_line)
    MyString = MyString.strip("'[]")
    TempFile.write(MyString)


MyFile.close()
TempFile.close()

My input looks like this:

1 Jargon
2 Python
3 Yada Yada
4 Stuck

My output when I do this is:

JargonPythonYada YadaStuck

I then modify the source code to this:

import string, io

FileName = input("Arb File Name (.txt): ")

MyFile = open(FileName, 'r')

TempFile = open('TempFile.txt', 'w', encoding='UTF-8')

for m_line in MyFile:
    m_line = m_line.strip()
    m_line = m_line.split(": ", 1)
    if len(m_line) > 1:
        del m_line[0]
    #print(m_line)
    MyString = str(m_line)
    MyString = MyString.strip("'[]")
    #print(MyString)
    TempFile.write('\n'.join(MyString))


MyFile.close()
TempFile.close()

Same input and my output looks like this:

J
a
r
g
o
nP
y
t
h
o
nY
a
d
a

Y
a
d
aS
t
u
c
k

Ideally, I would like each of the words to appear on a seperate line without the numbers in front of them.

Thanks,

MarleyH


You have to write the '\n' after each line, since you're stripping the original '\n'; Your idea of using '\n'.join() doesn't work because it will use\n to join the string, inserting it between each char of the string. You need a single \n after each name, instead.

import string, io

FileName = input("Arb file name (.txt): ")

with open(FileName, 'r') as MyFile:
    with open('TempFile.txt', 'w', encoding='UTF-8') as TempFile:
        for line in MyFile:
            line = line.strip().split(": ", 1)
            TempFile.write(line[1] + '\n')


fileName = input("Arb file name (.txt): ")
tempName = 'TempFile.txt'

with open(fileName) as inf, open(tempName, 'w', encoding='UTF-8') as outf:
    for line in inf:
        line = line.strip().split(": ", 1)[-1]

        #print(line)
        outf.write(line + '\n')

Problems:

  1. the result of str.split() is a list (this is why, when you cast it to str, you get ['my item']).

  2. write does not add a newline; if you want one, you have to add it explicitly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜