Py学习  »  Python

如何用python代码读取外部路径中的文件?

Job • 4 年前 • 610 次点击  

我有一个文本文件。但我不想直接在python脚本中输入该文件。我想从命令行运行我的python脚本,参数是我的文本文件。我想要的命令行是:$python.exe script.py c:/user/text_file.txt。然后,文本文件将放入in file(在python脚本中)并执行该过程。

这段代码返回我打印脚本中的所有单词。看起来像这样: [[],[],['im','po','rt',',',,,['de','f','ma','in','(a','rg']]

 import sys

    def main():
        infile = sys.argv[0]
        Array = ["f4", "f3", "f2", "f1"]
        with open(infile, "r") as input_file:
            output_list = []
            for rec in input_file.read().splitlines():
                rec = rec[:-3]
                FBlist = [rec[i:i+2] for i in range(0, len(rec), 2)]
                output_list.append(FBlist)
                print(output_list)



    main()

我修改了我的问题。我误解了先前的问题。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40263
 
610 次点击  
文章 [ 2 ]  |  最新文章 4 年前
S. Regelin
Reply   •   1 楼
S. Regelin    5 年前

如果我正确理解你的话,文件的路径就不会改变。只是从更改启动python脚本的目录。在目录中找不到该文件 C:\用户,因为我不在此目录中。您只需使用上述文件的绝对路径:

file = open('C:\User\X\Data\1.txt', 'r')
print(file.read())
file.close()

或者,如果每次都可以使用相对路径从同一目录(c:\ user)执行python脚本:

file = open('X\Data\1.txt', 'r')
print(file.read())
file.close()
Caleb Goodman
Reply   •   2 楼
Caleb Goodman    5 年前

只需使用:

file = open('yourFilePathHere', 'r')
print(file.read())
file.close()