此部分代码应将输入和另一个变量(Score)写入文本文件。程序要求输入(因此if语句肯定正在运行)并且运行没有错误,但文本文件为空。奇怪的是,将此代码复制到空的python文件并运行它可以正常工作。这里发生了什么?
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
Name = input("What is your name?")
BestOf = open("High Scores.txt", "w").close()
BestOf = open("High Scores.txt", "a")
BestOf.write(Name + "\n")
BestOf.write(str(Score))
答案 0 :(得分:1)
附加后我没有关闭文件。
BestOf.close()
修好了
答案 1 :(得分:0)
尝试以'w +'模式打开文件。如果文件不存在,这将创建该文件。 您还可以使用'os'模块检查文件是否退出。
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name="Users")
public class Users {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="User_ID")
private int ID;
@Column(name="User_first_name")
@NotEmpty(message="Field cannot be left blank")
private String First_Name;
@Column(name="user_last_name")
private String Last_Name;
@Column(name="user_contact")
private int Contact;
@Column(name="user_email")
private String Email;
@Column(name="user_date_birth")
@DateTimeFormat(pattern="dd/MM/yyyy")
private Date DateOfBirth;
@Column(name="user_joining_date")
private Date DateOfJoining;
@Column(name="user_salary")
@NotNull
private int Salary;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public int getContact() {
return Contact;
}
public void setContact(int contact) {
Contact = contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public Date getDateOfJoining() {
return DateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
DateOfJoining = dateOfJoining;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
}