如何在Python中正确更改文件路径的名称? [英] How do I change the name of a file path correctly in Python?
问题描述
我的代码
specFileName = input("Enter the file path of the program you would like to capslock: ")
inFile = open(specFileName, 'r')
ified = inFile.read().upper()
outFile = open(specFileName + "UPPER", 'w')
outFile.write(ified)
outFile.close()
print(inFile.read())
这基本上是使任何文件都大写,然后将其放入名为UPPER文件名"的新文件中.如何将"UPPER"位添加到变量中,而不必在变量的末尾或开头?由于开头的文件路径的其余部分和结尾的文件扩展名,因此无法正常工作.例如,C:/users/me/directory/file.txt将变为C:/users/me/directory/UPPERfile.txt
This is basically make to take in any file, capitalize everything, and put it into a new file called UPPER"filename". How do I add the "UPPER" bit into the variable without it being at the very end or very beginning? As it won't work like that due to the rest of the file path in the beginning and the file extension at the end. For example, C:/users/me/directory/file.txt would become C:/users/me/directory/UPPERfile.txt
推荐答案
取决于您到底要如何执行此操作,有几种方法.
Depending on exactly how you're trying to do this, there's several approaches.
首先,您可能只想获取文件名,而不是整个路径.使用 os.path.split
.>
First of all you probably want to grab just the filename, not the whole path. Do this with os.path.split
.
>>> pathname = r"C:\windows\system32\test.txt"
>>> os.path.split(pathname)
('C:\\windows\\system32', 'test.txt')
然后,您还可以查看 os.path.splitext
Then you can also look at os.path.splitext
>>> filename = "test.old.txt"
>>> os.path.splitext(filename)
('test.old', '.txt')
最后,字符串格式化会很好
And finally string formatting would be good
>>> test_string = "Hello, {}"
>>> test_string.format("world") + ".txt"
"Hello, world.txt"
将它们放在一起,您可能会遇到类似这样的情况:
Put 'em together and you've probably got something like:
def make_upper(filename, new_filename):
with open(filename) as infile:
data = infile.read()
with open(new_filename) as outfile:
outfile.write(data.upper())
def main():
user_in = input("What's the path to your file? ")
path = user_in # just for clarity
root, filename = os.path.split(user_in)
head,tail = os.path.splitext(filename)
new_filename = "UPPER{}{}".format(head,tail)
new_path = os.path.join(root, new_filename)
make_upper(path, new_path)
这篇关于如何在Python中正确更改文件路径的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!