Python附加文件

时间:2018-05-21 03:11:06

标签: python

我正在尝试循环,基本上在文件末尾添加一行。尽管循环有效,但它会将所有文件输出到桌面上,而不会修改文件。此外,它删除所有内容,只是在文件中添加Vcomb的内容。

干杯们,我确定我在这里做错了什么。

import os

print("Enter Date & Time: (YYYYMMDDhhmm)")
vdate = input()
vline = "VERIFY  48:0x"+vdate


print("Please Use: Verified by:___(Full name)____ on ___(Date)___")
vname = input()
vcomments = "       // " +vname

Vcomb = vline+vcomments
print (Vcomb)

print("Copy paste full directory path here")
directory = input()

for filename in os.listdir(directory):
    if filename.endswith(".ADC"):
        f = open(filename, 'a')
        f.write(Vcomb)
        f.close()

1 个答案:

答案 0 :(得分:2)

os.listdir()方法将只返回文件名,但它不具有文件的完整路径。因此,每次运行时,程序都会在您运行它的位置创建新文件。

例如,如果我的目录中有3个文件(a.txt,b.txt,c.txt)(D:\ Data \ Test),os.listdir()将只返回a.txt,b。 TXT,c.txt。所以你需要添加目录路径。希望以下代码能为您提供帮助。

import os
print("Enter Date & Time: (YYYYMMDDhhmm)")
vdate = input()
vline = "VERIFY  48:0x"+vdate


print("Please Use: Verified by:___(Full name)____ on ___(Date)___")
vname = input()
vcomments = "       // " +vname

Vcomb = vline+vcomments
print (Vcomb)

print("Copy paste full directory path here")
directory = input()
print(directory)
for filename in os.listdir(directory):
    print(filename)
    if filename.endswith(".ADC"):
        f = open(os.path.join(directory, filename),'a')
        f.write(Vcomb)
        f.close()

希望它有所帮助!! 快乐编码:)