Python 3中的行替换

时间:2018-03-19 23:23:21

标签: python-3.x replace

我是一名新的编码员,他在Python 3中接​​受了一些兼职培训,最近我给了一个家庭作业来编写一个程序,允许用户输入文件的名称,输入他们想要改变的文本。该文件,然后更改它。 我写了一些代码,并正在试验" r +"功能,但我的代码似乎没有工作。我一直试图在我测试的.txt文件中更改的行不会改变 如果有人能给我一些提示,我将非常感激。

# Build main

def main():
# Get file name and open for reading and writing
    toalter = input("Please enter a target file: ")
    infile = open(toalter, "r+")
# Get input of the line to be changed, and what it is to change to
    old = input("Please enter the text you want to change: ")
    new = input("Please enter what you want it changed to: ")

    for line in infile:
        if old in line:
            line = line.replace(old, new)
    infile.close()
main()

1 个答案:

答案 0 :(得分:0)

  1. 你用new替换了旧字符串,但是你从不调用语句将其写入" toalter"文件。
  2. 您无法同时打开文件进行读写,但您可以打开阅读,对该数据执行某些操作,然后再次打开以覆盖。
  3. 假设我有一个包含以下内容的test.txt文件。我想用椰子代替Apple。这就是我接近它的方式。

    Apple
    Orange
    Strawberry
    Kiwi
    
    >>> def replace (old, new):
    ...     path = '/testfiles/test.txt'
    ...     with open (path) as f:
    ...         file = f.read ()
    ...     if old in file:
    ...         file = file.replace (old, new)
    ...     with open (path, 'w') as f:
    ...         f.write (file)
    ...         
    >>> 
    >>> replace ('Apple', 'Coconut')
    

    <强>输出

    Coconut
    Orange
    Strawberry
    Kiwi
    

    如果您的文件包含多个Apple实例,那么您需要将逻辑更改为此。

    def replace (old, new):
    ...     newstring = ''
    ...     path = '/testfiles/test.txt'
    ...     with open (path) as f:
    ...         for line in f:
    ...             if old in line:
    ...                 newstring += line.replace (old, new)
    ...             else:
    ...                 newstring += line
    ...     with open (path, 'w') as f:
    ...         f.write (newstring)
    ...         
    >>> 
    
相关问题