为什么一开始写到.txt文件就会删除现有的字符呢?抱歉我的无知,我已经很久没有编程了。
Alabama[edit]
Auburn (Auburn University)[1]
Florence (University of North Alabama)
Jacksonville (Jacksonville State University)[2]
Livingston (University of West Alabama)[2]
Montevallo (University of Montevallo)[2]
Troy (Troy University)[2]
Tuscaloosa (University of Alabama, Stillman College, Shelton State)[3][4]
Tuskegee (Tuskegee University)[5]
f =open('university_towns.txt',"r+")
f.write('T\n')
f.close()
T
bama[edit]
Auburn (Auburn University)[1]
Florence (University of North Alabama)
Jacksonville (Jacksonville State University)[2]
Livingston (University of West Alabama)[2]
Montevallo (University of Montevallo)[2]
Troy (Troy University)[2]
Tuscaloosa (University of Alabama, Stillman College, Shelton State)[3][4]
Tuskegee (Tuskegee University)[5]
要追加到一个文件中,你需要用'a+'来代替'r+'的 "open"(见 此处)
所以在你的情况下。
f =open('university_towns.txt',"a+")
f.write('T\n')
f.close()