如何使用Python代码更改路径文件中的文件? [英] How to read a file in changing path file with Python code?

查看:123
本文介绍了如何使用Python代码更改路径文件中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我想从cmd运行这个python脚本:C:\ User \ X \ Data> PyScript.py。它可以读取Test.txt文件。因为此路径中的Test.txt文件> C:\User\X\Data> 

但是,我想从cmd运行我的python脚本:C:\ User> C:\ User \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Test.txt





我尝试过:



 Input_file = open(  Test.txt  r

print (Input_file.read())

解决方案

如果文件不在当前目录中,在上面的例子中是 C:\ User ,那么你必须在 open 语句中提供完整路径。更好的想法是在命令中提供文件名,例如:

 C:\ User> C:\ User \ X \ Data \\ \\ PyScript.py C:\ User \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ > sys.argv ,如 sys  - 系统特定的参数和功能中所述 -  Python 3.7.2文档 [ ^ ]。


您可以使用(在您的脚本中)Test.txt文件的绝对路径或更改工作目录你的脚本(这里的一些想法: python:更改脚本工作目录到脚本自己的目录 - Stack Overflow [ ^ ])。


The problem : I want to run this python script from cmd: C:\User\X\Data>PyScript.py. It can read the Test.txt file. Because the Test.txt file in this path > C:\User\X\Data>

But, I want to run my python script from cmd : C:\User>C:\User\X\Data\PyScript.py It return, no such file firectory "Test.txt"



What I have tried:

Input_file = open ("Test.txt", "r")

print (Input_file.read())

解决方案

If the file is not in the current directory, which in the above case is C:\User, then you must provide the full path in your open statement. A better idea would be to provide the file name in the command, like:

C:\User>C:\User\X\Data\PyScript.py C:\User\X\Data\Test.txt


Then in your python code you just need to use sys.argv as described in sys — System-specific parameters and functions — Python 3.7.2 documentation[^].


You either use (in your script) the absolute path of the "Test.txt" file or change the working directory of your script (some ideas here: python: Change the scripts working directory to the script's own directory - Stack Overflow[^]).


这篇关于如何使用Python代码更改路径文件中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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