如何在Python中正确更改文件路径的名称?
我的代码如何在Python中正确更改文件路径的名称?,python,filenames,Python,Filenames,我的代码 这基本上是为了接收任何文件,将所有内容大写,然后将其放入一个名为UPPER“filename”的新文件中。如何将“上限”位添加到变量中,而不使其位于最末尾或最开头?因为它不会像那样工作,因为文件路径的其余部分在开头,文件扩展名在结尾。例如,C:/users/me/directory/file.txt将变成C:/users/me/directory/UPPERfile.txt查看模块中的方法os.path.split和os.path.splitext 另外,快速提醒:别忘了关闭你的“填充
这基本上是为了接收任何文件,将所有内容大写,然后将其放入一个名为UPPER“filename”的新文件中。如何将“上限”位添加到变量中,而不使其位于最末尾或最开头?因为它不会像那样工作,因为文件路径的其余部分在开头,文件扩展名在结尾。例如,C:/users/me/directory/file.txt将变成C:/users/me/directory/UPPERfile.txt查看模块中的方法
os.path.split
和os.path.splitext
另外,快速提醒:别忘了关闭你的“填充”。根据你的具体操作方式,有几种方法 首先,您可能只想获取文件名,而不是整个路径。用你的手做这个 然后你也可以看看 最后,字符串格式也不错
>>> filename = "test.old.txt"
>>> os.path.splitext(filename)
('test.old', '.txt')
把它们放在一起,你可能会得到:
>>> test_string = "Hello, {}"
>>> test_string.format("world") + ".txt"
"Hello, world.txt"
你想把它放在哪里?@Padraic Cunningham放在文件名的开头,而不是文件路径的开头。例如,C:/users/me/directory/file.txt将成为C:/users/me/directory/UPPERfile.txt的可能副本
>>> filename = "test.old.txt"
>>> os.path.splitext(filename)
('test.old', '.txt')
>>> test_string = "Hello, {}"
>>> test_string.format("world") + ".txt"
"Hello, world.txt"
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)