Python Regex 脚本排序并打印到新文档

Python Regex Script sort and print to new document

所以我正在尝试编写一些代码来扫描 ID 之间有一堆混乱的 .txt 文件。我想找到特定的字符串,在它们之前创建一个新行,然后打印到一个新文档中。目前,我的代码如下所示:

from__future__import print_function
import re
NDoc = raw_input("Enter name of new document")".txt"
log = open("C:Python27\NDoc.txt", 'w')
file = raw_input("Enter a file to be sorted")
xfile = open(file)

for line in xfile:
    l=line.strip()
    n=re.sub("(\B)(?=((MTH|ENG|SCN|HST)[|]))","\n",line)

if len(n) > 0:
    nl=split.("\n")
    for item in nl:
        print(item)

当我 运行 这个时,我得到一个 Eroor [errno2] No such file or directory: 'xxx' where xxx = whatever my input was for the variable "file."

我不确定该怎么做,因为我很确定我正在目录中输入文件。

此外,附带说明一下,此代码是否会创建一个新文件并使用 open('filename', 'w') 行打印到其中?

您有 ".txt" 会抛出此错误 SyntaxError: invalid syntax,因此您应该使用 +".txt"file 变量也是如此。

>>> NDoc = raw_input("Enter name of new document")".txt"
SyntaxError: invalid syntax
>>> NDoc = raw_input("Enter name of new document") + ".txt"
Enter name of new documentsomefile
>>> NDoc
'somefile.txt'
>>>