就地文件字符串替换-Windows错误 [英] Inplace file string replacement - windows error

查看:31
本文介绍了就地文件字符串替换-Windows错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现此处给出的答案:

I am trying to implement the answer given here:

https://stackoverflow.com/a/1388570/1461850

我有一个输入文件 zzz.txt 包含:

I have an input file zzz.txt containing:

potato potato potato potato potato potato potato potato potato 
potato potato potato
potato potato potato potato potato potato potato potato potato
potato potato potato potato turnip potato
potato potato parsnip potato potato potato

我正在尝试用这样的方式替换单词:

I am trying to replace words inplace like so:

import fileinput
fileinput.close()
file = open('zzz.txt', "r+")
for line in fileinput.input(file, inplace=1):
    print line.replace('turnip', 'potato')

我收到以下错误:

Traceback (most recent call last):
  File "testss.py", line 19, in <module>
    for line in fileinput.input(file, inplace=1):
  File "c:\python27\lib\fileinput.py", line 253, in next
    line = self.readline()
  File "c:\python27\lib\fileinput.py", line 322, in readline
    os.rename(self._filename, self._backupfilename)
WindowsError: [Error 123] The filename, directory name, or volume label syntax i
s incorrect

我做错了什么吗?

推荐答案

而不是传递文件对象,而是将文件名(或文件名列表)传递给 fileinput.input :

Instead of passing the file object, pass the file name(or list of filenames) to fileinput.input:

fileinput.input('zzz.txt', inplace=1):

注意:请勿使用 file 作为变量名, file 是内置函数.

Note: Don't use file as a variable name, file is a built-in function.

这篇关于就地文件字符串替换-Windows错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆