简体   繁体   English

具有复杂参数的python函数

[英]A python function with a complicated argument

I have a function in a python code whose argument is as follows: 我在python代码中有一个函数,其参数如下:

save_geometry(r"""C:\Users\User0\Documents\test.txt """)

I want to modify the argument and be able to save to a different path with a different filename: 我想修改参数并能够使用不同的文件名保存到其他路径:

filename = "geometries.txt "
filepath = "D:/AllData/"
filefullpath = filepath + filename

Could someone help me how I should pass filefullpath to save_geometry ? 有人可以帮我如何将filefullpath传递给save_geometry吗? If there were no r in the argument of save_geometry , it would be easy. 如果save_geometry的参数中没有r ,那将很容易。 But I don't know how to deal with this r . 但我不知道该如何处理这个r

The r"" construct just tells Python that whatever's in the string should be interpreted as raw data. r“”结构只是告诉Python,字符串中的任何内容都应解释为原始数据。

"qw\n" == 'qw\n'
r"qw\n" == 'qw\\n'.

It's used because the "\\" path separator is also used for newlines and such. 之所以使用它,是因为“ \\”路径分隔符也用于换行符等。 You can skip it when putting in the argument; 您可以在输入参数时跳过它; save_geometry(filefullpath) should do what you expect. save_geometry(filefullpath)应该可以完成您的期望。

Note that the canonical way of putting together paths is os.path.join 请注意,将路径组合在一起的规范方法是os.path.join

path = os.path.join("D:\\", "AllData", "geometries.txt")

User3757614's answer addresses your concern of the raw string notation, but succinctly all the r"" notation does is tell Python that the following string should not treat \\ as an escape character, but as a literal backslash. User3757614的答案解决了您对原始字符串表示法的担忧,但是简洁的所有r""表示法是告诉Python后面的字符串不应将\\视为转义字符,而应视为文字反斜杠。 This is important since "C:\\new folder" is actually 这很重要,因为"C:\\new folder"实际上是

C:
ew folder

Since \\n is a newline. 由于\\n是换行符。

You cans use the os module to split your string into a folder path and file name. 您可以使用os模块将字符串拆分为文件夹路径和文件名。

eg 例如

import os
pathname = os.path.dirname('C:\Users\User0\Documents\test.txt')  #C:\Users\User0\Documents
filename = os.path.basename('C:\Users\User0\Documents\test.txt')  #test.txt

Though you'll need to modify your path string because your \\ s will be interpreted and newline bytes 尽管您将需要修改路径字符串,因为您的\\ s将被解释并且换行字节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM