python - python 中的 input() 和\n 字符

标签 python python-3.x

我试图使用 input() 查找并替换多个文件中的多行纯文本,但是当我输入 '\n' 字符来表示新行字符在文本中的位置时,它找不到它并且不会取代它。

我尝试使用 raw_strings 但无法让它们工作。

这是正则表达式的工作吗?

python 3.7

import os
import re
import time

start = time.time()
# enter path and check input for standard format
scan_folder = input('Enter the absolute path to scan:\n')
validate_path_regex = re.compile(r'[a-z,A-Z]:\\?(\\?\w*\\?)*')
mo = validate_path_regex.search(scan_folder)
if mo is None:
    print('Path is not valid. Please re-enter path.\n')
    import sys
    sys.exit()
os.chdir(scan_folder)
# get find/replaceStrings, and then confirm that inputs are correct.
find_string = input('Enter the text you wish to find:\n')
replace_string = input('Enter the text to replace:\n')
permission = input('\nPlease confirm you want to replace '
                   + find_string + ' with '
                   + replace_string + ' in ' + scan_folder
                   + ' directory.\n\nType "yes" to continue.\n')
if permission == 'yes':
    change_count = 0
    # Context manager for results file
    with open('find_and_replace.txt', 'w') as results:
        for root, subdirs, files in os.walk(scan_folder):
            for file in files:
                # ignore files that don't endwith '.mpr'
                if os.path.join(root, file).endswith('.mpr'):
                    fullpath = os.path.join(root, file)
                    # context manager for each file opened
                    with open(fullpath, 'r+') as f:
                        text = f.read()
                        # only add to changeCount if find_string is in text
                        if find_string in text:
                            change_count += 1
                        # move cursor back to beginning of the file
                        f.seek(0)
                        f.write(text.replace(find_string, replace_string))
        results.write(str(change_count)
        + ' files have been modified to replace '
        + find_string + ' with ' + replace_string + '.\n')
    print('Done with replacement')
else:
    print('Find and replace has not been executed')
end = time.time()
print('Program took ' + str(round((end - start), 4)) + ' secs to complete.\n')

find_string = BM="LS"\nTI="12"\nDU="7" Replace_string = BM="LSL"\nDU="7"

原始文件看起来像

BM="LS"
TI="12"
DU="7" 

我希望将其更改为

BM="LSL"
DU="7" 

但文件没有改变。

最佳答案

因此,您的误解是源代码之间的区别,源代码理解转义序列,例如“这是一个包含两行的字符串\n”,以及诸如“原始字符串”(在这种情况下没有意义的概念)之类的内容以及您作为用户输入提供的数据。 input 函数基本上处理来自标准输入设备的数据。当您向标准输入提供数据时,它会被解释为原始字节,然后输入函数假定其为文本(使用系统设置暗示的任何内容进行解码)。有两种方法允许用户输入换行符,第一种是使用 sys.stdin,但是,这需要您提供 EOF,可能使用 ctrl + D:

>>> import sys
>>> x = sys.stdin.read()
here is some text and i'm pressing return
to make a new line. now to stop input, press control d>>> x
"here is some text and i'm pressing return\nto make a new line. now to stop input, press control d"
>>> print(x)
here is some text and i'm pressing return
to make a new line. now to stop input, press control d

这不太人性化。您必须传递换行符和EOF,即return + ctrl + D或执行 ctrl + D 两次,我相信这取决于系统。

更好的方法是允许用户输入转义序列,然后自己解码它们:

>>> x = input()
I want this to\nbe on two lines
>>> x
'I want this to\\nbe on two lines'
>>> print(x)
I want this to\nbe on two lines
>>> x.encode('utf8').decode('unicode_escape')
'I want this to\nbe on two lines'
>>> print(x.encode('utf8').decode('unicode_escape'))
I want this to
be on two lines
>>>

关于python - python 中的 input() 和\n 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56708764/

相关文章:

python - Python 库中的命名约定

python - 如何在 Python/Windows 中列出网络接口(interface)及其配置 IP、网络掩码和网关

python - 子类化日期时间 : Is there a better way to maintain resulting object type after arithmetic operations?

python - 嵌套生成器表达式 - 意外结果

python-3.x - Pandas 数据帧 read_excel : How to look for empty cells?

python - 将 excel 或 csv 文件转换为 pandas 多级数据框

python - 使用 Python 导入我们的脚本

python-3.x - Mask rcnn 不适用于高分辨率图像

python - python中的异常错误处理在指定不执行后吐出错误

python - 如何在 Python 中使用 Dict 创建多个组合的列表