英文:
Taking txt files with unknown names as parameters (Python)
问题
我正在尝试在PyCharm中编写一个程序,该程序可以接受2个txt文件的名称作为输入,然后使用该输入来执行一些指令。我了解我可以将txt文件的名称放在配置的参数中,但在事先不知道文件名的情况下,我该如何做呢?目前,代码片段非常模糊,但如果没有传递这两个txt文件,我无法进行测试运行。
import sys
sets = sys.argv[1]
operations = sys.argv[2]
print(len(sys.argv))
print(sets)
print(operations)
即使我尝试在配置中将txt文件的名称硬编码为参数,我仍然只能得到文件的名称,所以我知道我有不止一个问题 😓。
英文:
I am trying to write a program in Pycharm that can take the name of 2 txt files as an input and then use that input to execute some set of instructions. I understand I can put the name of a txt file in the parameters of the configuration, but how can I do that without knowing what the file name will be beforehand? The code snippet is very vague so far but I can't really do test runs without passing the 2 txt files.
import sys
sets = sys.argv[1]
operations = sys.argv[2]
print(len(sys.argv))
print(sets)
print(operations)
Even when I've tried hard-coding names of txt-files as parameters in the configuration I only get back the names of the files so I know I have more problems than one 😬.
答案1
得分: 0
I understand. Here is the translated content:
"我明白我可以将一个txt文件的名称放在配置的参数中,但在事先不知道文件名的情况下,我该如何做呢。"
为了使用在编写代码时未知的参数,比如文件名,你可以在终端执行Python文件时将这些变量作为参数传递。
"即使我尝试在配置中硬编码txt文件的名称作为参数,我只会得到文件的名称而已。"
如果你想处理文件内的文本内容,你需要首先打开这些文件,不能像这样只是打印它们:print("file1.txt")
示例代码:
import sys
file1 = sys.argv[1]
file2 = sys.argv[2]
print(f"打开并读取文件:{file1}")
with open(file1, "r") as f:
print(f.read())
print(f"打开并读取文件:{file2}")
with open(file2, "r") as f:
print(f.read())
执行代码(在终端中运行):
python test.py test1.txt test2.txt
输出:
打开并读取文件:test1.txt
Hello World
This is file test1
打开并读取文件:test2.txt
Hello Stackoverflow
This is test2
英文:
> "I understand I can put the name of a txt file in the parameters of
> the configuration, but how can I do that without knowing what the file
> name will be beforehand."
In order to work with parameters unknown at the time you write your code, a filename for example in your case, you can pass those variables when you execute your python file in the terminal as arguments.
> "Even when I've tried hard-coding names of txt-files as parameters in
> the configuration I only get back the names of the files"
If you want to work with the text inside the files you need to open the files first, you can't just print them like print("file1.txt")
Code example:
import sys
file1 = sys.argv[1]
file2 = sys.argv[2]
print(f"Open and read file: {file1}")
with open(file1, "r") as f:
print(f.read())
print(f"Open and read file: {file2}")
with open(file2, "r") as f:
print(f.read())
Executing code (run in terminal):
python test.py test1.txt test2.txt
Output:
Open and read file: test1.txt
Hello World
This is file test1
Open and read file: test2.txt
Hello Stackoverflow
This is test2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论