簡體   English   中英

Python的file.write()方法和字符串處理問題

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

我目前遇到的問題(是Python的新手)正在將字符串寫入文本文件。 我遇到的問題是,要么字符串之間沒有換行符,要么每個字符后都有換行符。 遵循的代碼:

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()

我的輸入如下所示:

1 Jargon
2 Python
3 Yada Yada
4 Stuck

執行此操作時,我的輸出是:

JargonPythonYada YadaStuck

然后,我將源代碼修改為:

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()

相同的輸入,我的輸出如下所示:

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

Y
a
d
aS
t
u
c
k

理想情況下,我希望每個單詞都出現在單獨的行中,而前面沒有數字。

謝謝,

馬利

您必須在每行之后寫上'\\n' ,因為您要剝離原始的'\\n' 您使用'\\n'.join()想法行不通,因為它將使用\\n來連接字符串,並將其插入到字符串的每個字符之間。 每個名稱后都需要一個\\n來代替。

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')

問題:

  1. str.split()的結果是一個列表(這就是為什么將其強制轉換為str時會得到['my item'])。

  2. 寫不會添加換行符; 如果需要,則必須顯式添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM