python - 如何更改文本文件中的行?

标签 python text

我正在尝试格式化 .txt 文件中的文本。内容也在一个 xml 中,但我复制到一个文本文件,我正在尝试这样做。目前设置如下:

Pufferfish  Ocean
Anchovy Ocean
Tuna    Ocean
Sardine Ocean
Bream   River
Largemouth_Bass Mountain_Lake
Smallmouth_Bass River
Rainbow_Trout   River

我想弄清楚如何打开文件并将每一行转换为:

('Pufferfish', 'Ocean')

有办法吗?

这是我目前正在尝试的,我知道这是错误的,我正在尝试查找正确的语法和更改“str”的方式:

f1 = open('fish.txt', 'r')
f2 = open('fish.txt.tmp', 'w')

for line in f1:
    f2.write(line.replace(' ', ','))
    for word in line:
        f2.write(word.append('(', [0]))
        f2.write(word.append(')', (len(word))))
f1.close()
f2.close()

最佳答案

你可能需要这样的东西:

with open('input.txt') as input, open("output.txt", "a") as output:
    for line in input:
        output.write(str(tuple(line.split()))+"\n")

输出:

('Pufferfish', 'Ocean')
('Anchovy', 'Ocean')
('Tuna', 'Ocean')
('Sardine', 'Ocean')
('Bream', 'River')
('Largemouth_Bass', 'Mountain_Lake')
('Smallmouth_Bass', 'River')
('Rainbow_Trout', 'River')

关于python - 如何更改文本文件中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461656/

相关文章:

python - 由 <function check_errors.<locals>.wrapper at 0x10deb92f0> 启动的线程中出现未处理的异常

Android 如何使用 Intent 发送文本和图像或任何对象?

python - 如何向这些矩形添加文本?

java - jSoup 将 DIV 标签中的文本提取到字符串

python - 如何替换txt文件中的word

python - Python 程序和 MySQL 之间失去连接

python - 将字符串中的字母更改为字母和频率-python的数字

python - ipython 中的调试器不工作

Python sqlite 事务

html - 文本宽度随屏幕宽度变化