python文件writetext_逐行编写Python文本文件(write a text file in Python, line by line)

逐行编写Python文本文件(write a text file in Python, line by line)

我需要逐行写一个文本文件。 此代码逐行打印文本,但只有最后一行存储在result.txt文件中。

import re

import fileinput

for line in fileinput.input("test.txt"):

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

print new_str

open('result.txt', 'w').write(new_str)

I need to write a text file, line by line. This code is printing a text line by line, but only the last line is stored in the result.txt file.

import re

import fileinput

for line in fileinput.input("test.txt"):

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

print new_str

open('result.txt', 'w').write(new_str)

原文:https://stackoverflow.com/questions/18287658

更新时间:2020-07-11 13:07

最满意答案

我不知道为什么你需要fileinput模块, open也可以处理这种情况。

你的for循环遍历所有行并用新行覆盖 new_str 。 最后一行没有下一行,因此不会被覆盖,因此它是唯一可以保存的行。import re

test_f = open('test.txt')

result_f = open('result.txt', 'a')

for line in test_f:

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

result_f.write(new_str)

# also, this too, please:

test_f.close()

result_f.close()

即使代码崩溃,您也应该使用with语句自动关闭文件。import re

with open('test.txt') as test_f, open('result.txt', 'w') as result_f:

for line in test_f:

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

result_f.write(new_str)

I don't know why you need the fileinput module, open can handle this case as well.

Your for-loop goes through all lines and overrides new_str with the new line. The last line has no next line, so it won't be overridden, so it's the only line that will get saved. import re

test_f = open('test.txt')

result_f = open('result.txt', 'a')

for line in test_f:

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

result_f.write(new_str)

# also, this too, please:

test_f.close()

result_f.close()

You should use the with statement to automatically close your files even when your code crashes. import re

with open('test.txt') as test_f, open('result.txt', 'w') as result_f:

for line in test_f:

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

result_f.write(new_str)

2013-08-17

相关问答

这是使用enumerate解决方案: with open("in3.txt") as f:

lines = f.readlines()

with open("out.txt", "w") as f1:

for x, line in enumerate(lines): # Changed to enumerate as per recommendation

y = x*10

f1.write("\n00:01:"+str

...

我知道解释如何做这样的事情的一般指导方针是更好的形式,但对于像这样的简单任务,代码本身就说明了,真的...... 我会像这样实现它。 from pprint import pprint # For nicer formatting of the output.

# For the sake of a self-contained example,

# the data is inlined here.

#

# `f` could be replaced with `open('log.txt'

...

在文件中没有“替换现有行”这样的东西。 对于您想要执行的操作,您必须使用修改后的内容编写新文件,然后使用新文件替换旧文件。 示例代码: with open("old.file") as old, open("new.file", "w") as new:

for line in old:

line = modify(line.lstrip())

new.write(line + "\n")

os.rename("new.file", "old

...

只需更改您的代码: if( isset($_POST['submit']) ){

$name = $_POST['name'];

$age = $_POST['age'];

$address = $_POST['address'];

$file = fopen("student.txt","a");

...

我不确定我完全明白你在问什么,但我会尽力帮忙。 如果您尝试从文件中选择随机行,可以使用open() , readlines() , random.choice() : import random

line = random.choice(open("file").readlines())

如果您尝试从三个列表中的每一个中选择一个随机元素,则可以使用random.choice() : import random

choices=[random.choice(i) for i in lists]

...

尝试这个: with open('data.txt') as inf:

for line in inf:

num = line.strip()

if num:

fn = '%s.txt' %num

with open(fn, 'w') as outf:

outf.write('contains one line of text "%s"\n' %num)

使用with构造函数确

...

python中的文件I / O已经缓冲。 open()函数可以让您确定缓冲写入的范围: 可选的buffering参数指定文件所需的缓冲区大小: 0表示无缓冲, 1表示行缓冲,任何其他正值表示使用(大约)该大小的缓冲区。 负buffering意味着使用系统默认值,通常为tty设备进行行缓冲,并为其他文件进行完全缓冲。 如果省略,则使用系统默认值。 就个人而言,我通过with语句将该文件用作上下文管理器。 只要with suite下的所有语句(至少一个缩进级别更深)已完成或引发异常,文件对象就会关闭:

...

您的代码确实输出换行符。 检查您的编辑器是否识别\n换行符。 但是,它是偶然的。 writelines期望一系列的行: with open('output.txt','w', encoding='UTF-8') as output:

output.writelines(str(i)+'\n' for i in range(5))

Your code does output newlines. Check that your editor recognizes \n newlines. How

...

引用文档 , 要从文件中读取行,可以循环遍历文件对象。 这是内存高效,快速,并导致简单的代码 所以,我是你,我会这样做的 import os

wordReplacements = {'document':'file', 'notepad':'Notepad'}

def transform_line(line):

for key, value in wordReplacements.iteritems():

line = line.replace(key, value)

...

我不知道为什么你需要fileinput模块, open也可以处理这种情况。 你的for循环遍历所有行并用新行覆盖 new_str 。 最后一行没有下一行,因此不会被覆盖,因此它是唯一可以保存的行。 import re

test_f = open('test.txt')

result_f = open('result.txt', 'a')

for line in test_f:

new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)

result

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值